aboutsummaryrefslogtreecommitdiff
path: root/rpki/rtr/server.py
blob: a1aacbeeca80ac65321c22c33d3c17f3007960ab (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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
# $Id$
#
# Copyright (C) 2014  Dragon Research Labs ("DRL")
# Portions copyright (C) 2009-2013  Internet Systems Consortium ("ISC")
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notices and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND DRL AND ISC DISCLAIM ALL
# WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL DRL OR
# ISC 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.

"""
Server implementation for the RPKI-RTR protocol (RFC 6810 et sequalia).
"""

import os
import sys
import errno
import socket
import logging
import asyncore
import rpki.POW
import rpki.oids
import rpki.rtr.pdus
import rpki.rtr.channels

from rpki.rtr.pdus import (clone_pdu_root, CacheResponsePDU, EndOfDataPDU, CacheResetPDU, SerialNotifyPDU)


# Disable incremental updates.  Debugging only, should be False in production.
disable_incrementals = False

# These should be configurable in some sane fashion.
kickme_dir  = "sockets"
kickme_base = os.path.join(kickme_dir, "kickme")


class PDU(rpki.rtr.pdus.PDU):
  """
  Generic server PDU.
  """

  def send_file(self, server, filename):
    """
    Send a content of a file as a cache response.  Caller should catch IOError.
    """

    fn2 = os.path.splitext(filename)[1]
    assert fn2.startswith(".v") and fn2[2:].isdigit() and int(fn2[2:]) == server.version

    f = open(filename, "rb")
    server.push_pdu(CacheResponsePDU(version = server.version,
                                     nonce   = server.current_nonce))
    server.push_file(f)
    server.push_pdu(EndOfDataPDU(version = server.version,
                                 serial  = server.current_serial,
                                 nonce   = server.current_nonce,
                                 refresh = server.refresh,
                                 retry   = server.retry,
                                 expire  = server.expire))

  def send_nodata(self, server):
    """
    Send a nodata error.
    """

    server.push_pdu(ErrorReportPDU(version = server.version,
                                   errno = ErrorReportPDU.codes["No Data Available"],
                                   errpdu = self))


clone_pdu = clone_pdu_root(PDU)


@clone_pdu
class SerialQueryPDU(PDU, rpki.rtr.pdus.SerialQueryPDU):
  """
  Serial Query PDU.
  """

  def serve(self, server):
    """
    Received a serial query, send incremental transfer in response.
    If client is already up to date, just send an empty incremental
    transfer.
    """

    server.logger.debug(self)
    if server.get_serial() is None:
      self.send_nodata(server)
    elif server.current_nonce != self.nonce:
      server.logger.info("[Client requested wrong nonce, resetting client]")
      server.push_pdu(CacheResetPDU(version = server.version))
    elif server.current_serial == self.serial:
      server.logger.debug("[Client is already current, sending empty IXFR]")
      server.push_pdu(CacheResponsePDU(version = server.version,
                                       nonce   = server.current_nonce))
      server.push_pdu(EndOfDataPDU(version = server.version,
                                   serial  = server.current_serial,
                                   nonce   = server.current_nonce,
                                   refresh = server.refresh,
                                   retry   = server.retry,
                                   expire  = server.expire))
    elif disable_incrementals:
      server.push_pdu(CacheResetPDU(version = server.version))
    else:
      try:
        self.send_file(server, "%d.ix.%d.v%d" % (server.current_serial, self.serial, server.version))
      except IOError:
        server.push_pdu(CacheResetPDU(version = server.version))


@clone_pdu
class ResetQueryPDU(PDU, rpki.rtr.pdus.ResetQueryPDU):
  """
  Reset Query PDU.
  """

  def serve(self, server):
    """
    Received a reset query, send full current state in response.
    """

    server.logger.debug(self)
    if server.get_serial() is None:
      self.send_nodata(server)
    else:
      try:
        fn = "%d.ax.v%d" % (server.current_serial, server.version)
        self.send_file(server, fn)
      except IOError:
        server.push_pdu(ErrorReportPDU(version = server.version,
                                       errno   = ErrorReportPDU.codes["Internal Error"],
                                       errpdu  = self,
                                       errmsg  = "Couldn't open %s" % fn))


@clone_pdu
class ErrorReportPDU(rpki.rtr.pdus.ErrorReportPDU):
  """
  Error Report PDU.
  """

  def serve(self, server):
    """
    Received an ErrorReportPDU from client.  Not much we can do beyond
    logging it, then killing the connection if error was fatal.
    """

    server.logger.error(self)
    if self.errno in self.fatal:
      server.logger.error("[Shutting down due to reported fatal protocol error]")
      sys.exit(1)


def read_current(version):
  """
  Read current serial number and nonce.  Return None for both if
  serial and nonce not recorded.  For backwards compatibility, treat
  file containing just a serial number as having a nonce of zero.
  """

  if version is None:
    return None, None
  try:
    with open("current.v%d" % version, "r") as f:
      values = tuple(int(s) for s in f.read().split())
    return values[0], values[1]
  except IndexError:
    return values[0], 0
  except IOError:
    return None, None


def write_current(serial, nonce, version):
  """
  Write serial number and nonce.
  """

  curfn = "current.v%d" % version
  tmpfn = curfn + "%d.tmp" % os.getpid()
  with open(tmpfn, "w") as f:
    f.write("%d %d\n" % (serial, nonce))
  os.rename(tmpfn, curfn)


class FileProducer(object):
  """
  File-based producer object for asynchat.
  """

  def __init__(self, handle, buffersize):
    self.handle = handle
    self.buffersize = buffersize

  def more(self):
    return self.handle.read(self.buffersize)


class ServerWriteChannel(rpki.rtr.channels.PDUChannel):
  """
  Kludge to deal with ssh's habit of sometimes (compile time option)
  invoking us with two unidirectional pipes instead of one
  bidirectional socketpair.  All the server logic is in the
  ServerChannel class, this class just deals with sending the
  server's output to a different file descriptor.
  """

  def __init__(self):
    """
    Set up stdout.
    """

    super(ServerWriteChannel, self).__init__(root_pdu_class = PDU)
    self.init_file_dispatcher(sys.stdout.fileno())

  def readable(self):
    """
    This channel is never readable.
    """

    return False

  def push_file(self, f):
    """
    Write content of a file to stream.
    """

    try:
      self.push_with_producer(FileProducer(f, self.ac_out_buffer_size))
    except OSError, e:
      if e.errno != errno.EAGAIN:
        raise


class ServerChannel(rpki.rtr.channels.PDUChannel):
  """
  Server protocol engine, handles upcalls from PDUChannel to
  implement protocol logic.
  """

  def __init__(self, logger, refresh, retry, expire):
    """
    Set up stdin and stdout as connection and start listening for
    first PDU.
    """

    super(ServerChannel, self).__init__(root_pdu_class = PDU)
    self.init_file_dispatcher(sys.stdin.fileno())
    self.writer = ServerWriteChannel()
    self.logger = logger
    self.refresh = refresh
    self.retry = retry
    self.expire = expire
    self.get_serial()
    self.start_new_pdu()

  def writable(self):
    """
    This channel is never writable.
    """

    return False

  def push(self, data):
    """
    Redirect to writer channel.
    """

    return self.writer.push(data)

  def push_with_producer(self, producer):
    """
    Redirect to writer channel.
    """

    return self.writer.push_with_producer(producer)

  def push_pdu(self, pdu):
    """
    Redirect to writer channel.
    """

    return self.writer.push_pdu(pdu)

  def push_file(self, f):
    """
    Redirect to writer channel.
    """

    return self.writer.push_file(f)

  def deliver_pdu(self, pdu):
    """
    Handle received PDU.
    """

    pdu.serve(self)

  def get_serial(self):
    """
    Read, cache, and return current serial number, or None if we can't
    find the serial number file.  The latter condition should never
    happen, but maybe we got started in server mode while the cronjob
    mode instance is still building its database.
    """

    self.current_serial, self.current_nonce = read_current(self.version)
    return self.current_serial

  def check_serial(self):
    """
    Check for a new serial number.
    """

    old_serial = self.current_serial
    return old_serial != self.get_serial()

  def notify(self, data = None):
    """
    Cronjob instance kicked us: check whether our serial number has
    changed, and send a notify message if so.

    We have to check rather than just blindly notifying when kicked
    because the cronjob instance has no good way of knowing which
    protocol version we're running, thus has no good way of knowing
    whether we care about a particular change set or not.
    """

    if self.check_serial():
      self.push_pdu(SerialNotifyPDU(version = self.version,
                                    serial  = self.current_serial,
                                    nonce   = self.current_nonce))
    else:
      self.logger.debug("Cronjob kicked me but I see no serial change, ignoring")


class KickmeChannel(asyncore.dispatcher, object):
  """
  asyncore dispatcher for the PF_UNIX socket that cronjob mode uses to
  kick servers when it's time to send notify PDUs to clients.
  """

  def __init__(self, server):
    asyncore.dispatcher.__init__(self)                  # Old-style class
    self.server = server
    self.sockname = "%s.%d" % (kickme_base, os.getpid())
    self.create_socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    try:
      self.bind(self.sockname)
      os.chmod(self.sockname, 0660)
    except socket.error, e:
      self.server.logger.exception("Couldn't bind() kickme socket: %r", e)
      self.close()
    except OSError, e:
      self.server.logger.exception("Couldn't chmod() kickme socket: %r", e)

  def writable(self):
    """
    This socket is read-only, never writable.
    """

    return False

  def handle_connect(self):
    """
    Ignore connect events (not very useful on datagram socket).
    """

    pass

  def handle_read(self):
    """
    Handle receipt of a datagram.
    """

    data = self.recv(512)
    self.server.notify(data)

  def cleanup(self):
    """
    Clean up this dispatcher's socket.
    """

    self.close()
    try:
      os.unlink(self.sockname)
    except:                             # pylint: disable=W0702
      pass

  def log(self, msg):
    """
    Intercept asyncore's logging.
    """

    self.server.logger.info(msg)

  def log_info(self, msg, tag = "info"):
    """
    Intercept asyncore's logging.
    """

    self.server.logger.info("asyncore: %s: %s", tag, msg)

  def handle_error(self):
    """
    Handle errors caught by asyncore main loop.
    """

    self.server.logger.exception("[Unhandled exception]")
    self.server.logger.critical("[Exiting after unhandled exception]")
    sys.exit(1)


def _hostport_tag():
  """
  Construct hostname/address + port when we're running under a
  protocol we understand well enough to do that.  This is all
  kludgery.  Just grit your teeth, or perhaps just close your eyes.
  """

  proto = None

  if proto is None:
    try:
      host, port = socket.fromfd(0, socket.AF_INET, socket.SOCK_STREAM).getpeername()
      proto = "tcp"
    except:                             # pylint: disable=W0702
      pass

  if proto is None:
    try:
      host, port = socket.fromfd(0, socket.AF_INET6, socket.SOCK_STREAM).getpeername()[0:2]
      proto = "tcp"
    except:                             # pylint: disable=W0702
      pass

  if proto is None:
    try:
      host, port = os.environ["SSH_CONNECTION"].split()[0:2]
      proto = "ssh"
    except:                             # pylint: disable=W0702
      pass

  if proto is None:
    try:
      host, port = os.environ["REMOTE_HOST"], os.getenv("REMOTE_PORT")
      proto = "ssl"
    except:                             # pylint: disable=W0702
      pass

  if proto is None:
    return ""
  elif not port:
    return "/%s/%s" % (proto, host)
  elif ":" in host:
    return "/%s/%s.%s" % (proto, host, port)
  else:
    return "/%s/%s:%s" % (proto, host, port)


def server_main(args):
  """
  Implement the server side of the rpkk-router protocol.  Other than
  one PF_UNIX socket inode, this doesn't write anything to disk, so it
  can be run with minimal privileges.  Most of the work has already
  been done by the database generator, so all this server has to do is
  pass the results along to a client.
  """

  logger = logging.LoggerAdapter(logging.root, dict(connection = _hostport_tag()))

  logger.debug("[Starting]")

  if args.rpki_rtr_dir:
    try:
      os.chdir(args.rpki_rtr_dir)
    except OSError, e:
      sys.exit(e)

  kickme = None
  try:
    server = rpki.rtr.server.ServerChannel(logger = logger, refresh = args.refresh, retry = args.retry, expire = args.expire)
    kickme = rpki.rtr.server.KickmeChannel(server = server)
    asyncore.loop(timeout = None)
  except KeyboardInterrupt:
    sys.exit(0)
  finally:
    if kickme is not None:
      kickme.cleanup()


def listener_main(args):
  """
  Totally insecure TCP listener for rpki-rtr protocol.  We only
  implement this because it's all that the routers currently support.
  In theory, we will all be running TCP-AO in the future, at which
  point this listener will go away or become a TCP-AO listener.
  """

  # Perhaps we should daemonize?  Deal with that later.

  # server_main() handles args.rpki_rtr_dir.

  listener = None
  try:
    listener = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
    listener.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
  except:                               # pylint: disable=W0702
    if listener is not None:
      listener.close()
    listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  try:
    listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  except AttributeError:
    pass
  listener.bind(("", args.port))
  listener.listen(5)
  logging.debug("[Listening on port %s]", args.port)
  while True:
    try:
      s, ai = listener.accept()
    except KeyboardInterrupt:
      sys.exit(0)
    logging.debug("[Received connection from %r]", ai)
    pid = os.fork()
    if pid == 0:
      os.dup2(s.fileno(), 0)            # pylint: disable=E1103
      os.dup2(s.fileno(), 1)            # pylint: disable=E1103
      s.close()
      #os.closerange(3, os.sysconf("SC_OPEN_MAX"))
      server_main(args)
      sys.exit()
    else:
      logging.debug("[Spawned server %d]", pid)
      while True:
        try:
          pid, status = os.waitpid(0, os.WNOHANG) # pylint: disable=W0612
          if pid:
            logging.debug("[Server %s exited]", pid)
            continue
        except:                           # pylint: disable=W0702
          pass
        break


def argparse_setup(subparsers):
  """
  Set up argparse stuff for commands in this module.
  """

  # These could have been lambdas, but doing it this way results in
  # more useful error messages on argparse failures.

  def refresh(v):
    return rpki.rtr.pdus.valid_refresh(int(v))

  def retry(v):
    return rpki.rtr.pdus.valid_retry(int(v))

  def expire(v):
    return rpki.rtr.pdus.valid_expire(int(v))

  # Some duplication of arguments here, not enough to be worth huge
  # effort to clean up, worry about it later in any case.

  subparser = subparsers.add_parser("server", description = server_main.__doc__,
                                    help = "RPKI-RTR protocol server")
  subparser.set_defaults(func = server_main, default_log_to = "syslog")
  subparser.add_argument("--refresh", type = refresh, help = "override default refresh timer")
  subparser.add_argument("--retry",   type = retry,   help = "override default retry timer")
  subparser.add_argument("--expire",  type = expire,  help = "override default expire timer")
  subparser.add_argument("rpki_rtr_dir", nargs = "?", help = "directory containing RPKI-RTR database")

  subparser = subparsers.add_parser("listener", description = listener_main.__doc__,
                                    help = "TCP listener for RPKI-RTR protocol server")
  subparser.set_defaults(func = listener_main, default_log_to = "syslog")
  subparser.add_argument("--refresh", type = refresh, help = "override default refresh timer")
  subparser.add_argument("--retry",   type = retry,   help = "override default retry timer")
  subparser.add_argument("--expire",  type = expire,  help = "override default expire timer")
  subparser.add_argument("port",      type = int,     help = "TCP port on which to listen")
  subparser.add_argument("rpki_rtr_dir", nargs = "?", help = "directory containing RPKI-RTR database")