http.py 35.8 KB
Newer Older
Vincent Pelletier's avatar
Vincent Pelletier committed
1
# This file is part of caucase
2
# Copyright (C) 2017-2019  Nexedi
Vincent Pelletier's avatar
Vincent Pelletier committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#     Alain Takoudjou <alain.takoudjou@nexedi.com>
#     Vincent Pelletier <vincent@nexedi.com>
#
# caucase is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# caucase 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.
#
# You should have received a copy of the GNU General Public License
# along with caucase.  If not, see <http://www.gnu.org/licenses/>.
"""
Caucase - Certificate Authority for Users, Certificate Authority for SErvices
"""
21
from __future__ import absolute_import, print_function
Vincent Pelletier's avatar
Vincent Pelletier committed
22
import argparse
23
from collections import defaultdict
Vincent Pelletier's avatar
Vincent Pelletier committed
24
import datetime
25
import errno
Vincent Pelletier's avatar
Vincent Pelletier committed
26
from functools import partial
27
from getpass import getpass
Vincent Pelletier's avatar
Vincent Pelletier committed
28
import glob
29
import itertools
30
import json
Vincent Pelletier's avatar
Vincent Pelletier committed
31 32 33 34 35 36 37
import os
import socket
from SocketServer import ThreadingMixIn
import ssl
import sys
import tempfile
from threading import Thread
38
from urlparse import urlparse, urlunsplit
39
from wsgiref.simple_server import make_server, WSGIServer
40
import ipaddress
Vincent Pelletier's avatar
Vincent Pelletier committed
41 42
from cryptography import x509
from cryptography.hazmat.backends import default_backend
43 44
from cryptography.hazmat.primitives import serialization
import pem
45
from . import exceptions
Vincent Pelletier's avatar
Vincent Pelletier committed
46
from . import utils
47
from . import version
48
from .wsgi import Application, CORSTokenManager
49
from .ca import CertificateAuthority, UserCertificateAuthority, Extension
Vincent Pelletier's avatar
Vincent Pelletier committed
50
from .storage import SQLite3Storage
51
from .http_wsgirequesthandler import WSGIRequestHandler
Vincent Pelletier's avatar
Vincent Pelletier committed
52 53 54 55 56

_cryptography_backend = default_backend()

BACKUP_SUFFIX = '.sql.caucased'

57
def getBytePass(prompt): # pragma: no cover
58 59 60 61 62 63 64 65
  """
  Like getpass, but resurns a bytes instance.
  """
  result = getpass(prompt)
  if not isinstance(result, bytes):
    result = result.encode(sys.stdin.encoding)
  return result

66 67 68 69 70 71 72 73 74
def _createKey(path):
  """
  Open a key file, setting it to minimum permission if it gets created.
  Does not change umask, to be thread-safe.

  Returns a python file object, opened for write-only.
  """
  return os.fdopen(
    os.open(path, os.O_WRONLY | os.O_CREAT, 0o600),
75
    'wb',
76 77
  )

Vincent Pelletier's avatar
Vincent Pelletier committed
78 79 80 81 82 83 84
class ThreadingWSGIServer(ThreadingMixIn, WSGIServer):
  """
  Threading WSGI server
  """
  daemon_threads = True

  def __init__(self, server_address, *args, **kw):
Vincent Pelletier's avatar
Vincent Pelletier committed
85
    self._error_file = kw.pop('error_file', sys.stderr)
Vincent Pelletier's avatar
Vincent Pelletier committed
86
    self.address_family, _, _, _, _ = socket.getaddrinfo(*server_address)[0]
87 88 89 90 91 92 93
    WSGIServer.__init__(
      self,
      server_address,
      bind_and_activate=False,
      *args,
      **kw
    )
Vincent Pelletier's avatar
Vincent Pelletier committed
94

95 96 97 98 99 100
  def server_bind(self):
    if self.address_family == socket.AF_INET6:
      # Separate IPv6 and IPv4 port spaces
      self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
    WSGIServer.server_bind(self)

Vincent Pelletier's avatar
Vincent Pelletier committed
101 102 103 104 105 106 107 108 109 110
  def handle_error(self, request, client_address):
    """
    Handle an error gracefully.
    """
    utils.log_exception(
      error_file=self._error_file,
      exc_info=sys.exc_info(),
      client_address=client_address[0],
    )

111 112 113 114 115 116 117 118 119 120
  # pylint: disable=arguments-differ
  def serve_forever(self, *args, **kw):
    """
    Handle one request at a time until shutdown.

    In addition to python's version:
    - intercept EBADF on shutdown if select is interrupted:
    """
    try:
      return WSGIServer.serve_forever(self, *args, **kw)
Vincent Pelletier's avatar
Vincent Pelletier committed
121
    except socket.error as exception: # pragma: no cover
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
      # Workaround for the following unhandled error:
      # Traceback (most recent call last):
      #   File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
      #     self.run()
      #   File "/usr/lib/python2.7/threading.py", line 754, in run
      #     self.__target(*self.__args, **self.__kwargs)
      #   File "/usr/lib/python2.7/SocketServer.py", line 231, in serve_forever
      #     poll_interval)
      #   File "/usr/lib/python2.7/SocketServer.py", line 150, in _eintr_retry
      #     return func(*args)
      #   File "/usr/lib/python2.7/SocketServer.py", line 459, in fileno
      #     return self.socket.fileno()
      #   File "/usr/lib/python2.7/socket.py", line 228, in meth
      #     return getattr(self._sock,name)(*args)
      #   File "/usr/lib/python2.7/socket.py", line 174, in _dummy
      #     raise error(EBADF, 'Bad file descriptor')
      # error: [Errno 9] Bad file descriptor
      # Sadly, self.__shutdown_request is not accessible from here, so do not
      # check any further.
      if exception.errno != errno.EBADF:
        raise
  # pylint: enable=arguments-differ

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
def _buildQuoteCharList():
  # All chars considered guilty
  result = ['\\x%02x' % x for x in xrange(256)]
  # Exception for non-printable whitespaces.
  result[ord('\b')] = '\\b'
  result[ord('\n')] = '\\n'
  result[ord('\r')] = '\\r'
  result[ord('\t')] = '\\t'
  result[ord('\v')] = '\\v'
  # Exception for printable chars
  for x in xrange(0x20, 0x7f):
    result[x] = chr(x)
  # Exception in the exception: chars which need escapement
  result[ord('\\')] = '\\\\'
  result[ord('"')] = '\\"'
  return result
_QUOTE_LOG_LIST = _buildQuoteCharList()
del _buildQuoteCharList

Vincent Pelletier's avatar
Vincent Pelletier committed
164 165
class CaucaseWSGIRequestHandler(WSGIRequestHandler):
  """
Vincent Pelletier's avatar
Vincent Pelletier committed
166 167
  Make WSGIRequestHandler logging more apache-like and allow choosing a file
  other than stderr for log output.
Vincent Pelletier's avatar
Vincent Pelletier committed
168
  """
169
  server_version = 'caucased ' + version.__version__
Vincent Pelletier's avatar
Vincent Pelletier committed
170 171 172 173 174 175
  remote_user_name = '-'

  def __init__(self, *args, **kw):
    self._log_file = kw.pop('log_file', sys.stdout)
    self._error_file = kw.pop('error_file', sys.stderr)
    WSGIRequestHandler.__init__(self, *args, **kw)
176

Vincent Pelletier's avatar
Vincent Pelletier committed
177 178 179 180 181 182 183 184 185 186 187
  def log_date_time_string(self):
    """
    Apache-style date format.

    Compared to python's default (from BaseHTTPServer):
    - ":" between day and time
    - "+NNNN" timezone is displayed
    - ...but, because of how impractical it is in python to get system current
      timezone (including DST considerations), time it always logged in GMT
    """
    now = datetime.datetime.utcnow()
Vincent Pelletier's avatar
Vincent Pelletier committed
188 189 190
    return now.strftime(
      '%d/' + self.monthname[now.month] + '/%Y:%H:%M:%S +0000',
    )
Vincent Pelletier's avatar
Vincent Pelletier committed
191

192 193 194 195
  def log_request(self, code='-', size='-'):
    """
    Log request. Happens after response was sent.

Vincent Pelletier's avatar
Vincent Pelletier committed
196
    Compared to python's default (from BaseHTTPServer):
197 198 199 200 201 202 203 204 205 206 207 208 209 210
    - log referrer
    - log user agent
    - escaping
    """
    headers = getattr(self, 'headers', {})
    self.log_message(
      '"%s" %s %s "%s" "%s"',
      ''.join(_QUOTE_LOG_LIST[ord(x)] for x in self.requestline),
      code,
      size,
      ''.join(_QUOTE_LOG_LIST[ord(x)] for x in headers.get('Referrer', '-')),
      ''.join(_QUOTE_LOG_LIST[ord(x)] for x in headers.get('User-Agent', '-')),
    )

Vincent Pelletier's avatar
Vincent Pelletier committed
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
  # pylint: disable=redefined-builtin
  def log_message(self, format, *args):
    """
    Log an arbitrary message.

    Compared to python's default (from BaseHTTPServer):
    - make remote user name customisable (used in CaucaseSSLWSGIRequestHandler)
    - make output stream customisable
    - use print instead of plain .write(), for encoding purposes
    """
    print(
      '%s - %s [%s] %s' % (
        self.client_address[0],
        self.remote_user_name,
        self.log_date_time_string(),
        format % args,
      ),
      file=self._log_file,
    )
  # pylint: enable=redefined-builtin

  def get_stderr(self):
    """
    Send wsgi.errors to error output.
    """
    return self._error_file

Vincent Pelletier's avatar
Vincent Pelletier committed
238 239
class CaucaseSSLWSGIRequestHandler(CaucaseWSGIRequestHandler):
  """
240 241 242
  Add SSL-specific entries to environ:
  - HTTPS=on
  - SSL_CLIENT_CERT when client has sent a certificate.
Vincent Pelletier's avatar
Vincent Pelletier committed
243
  - use certificate serial as user name
Vincent Pelletier's avatar
Vincent Pelletier committed
244 245
  """
  def get_environ(self):
246 247 248
    """
    Populate environment.
    """
249
    environ = CaucaseWSGIRequestHandler.get_environ(self)
250
    environ['HTTPS'] = 'on'
Vincent Pelletier's avatar
Vincent Pelletier committed
251 252 253 254 255 256
    client_cert_der = self.request.getpeercert(binary_form=True)
    if client_cert_der is not None:
      cert = x509.load_der_x509_certificate(
        client_cert_der,
        _cryptography_backend,
      )
Vincent Pelletier's avatar
Vincent Pelletier committed
257
      self.remote_user_name = str(cert.serial_number)
Vincent Pelletier's avatar
Vincent Pelletier committed
258 259 260 261 262
      environ['SSL_CLIENT_CERT'] = utils.dump_certificate(cert)
    return environ

def startServerThread(server):
  """
263
  Create and start a "serve_forever" thread.
Vincent Pelletier's avatar
Vincent Pelletier committed
264 265 266 267 268
  """
  server_thread = Thread(target=server.serve_forever)
  server_thread.daemon = True
  server_thread.start()

269
def getSSLContext(
Vincent Pelletier's avatar
Vincent Pelletier committed
270 271 272
  key_len,
  threshold,
  server_key_path,
273 274
  hostname_ip_address,
  hostname_dnsname,
Vincent Pelletier's avatar
Vincent Pelletier committed
275
  cau,
276
  http_cas,
277
  renew=False, # Force renewal when True - used in tests
Vincent Pelletier's avatar
Vincent Pelletier committed
278 279 280
):
  """
  Build a new SSLContext with updated CA certificates, CRL and server key pair,
281
  and return it along with the datetime of next update.
Vincent Pelletier's avatar
Vincent Pelletier committed
282 283 284 285 286 287 288 289 290 291 292 293 294
  """
  ssl_context = ssl.create_default_context(
    purpose=ssl.Purpose.CLIENT_AUTH,
  )
  # SSL is used for client authentication, and is only required for very few
  # users on any given caucased. So make ssl_context even stricter than python
  # does.
  # No TLSv1 and TLSv1.1, leaving (currently) only TLSv1.2
  ssl_context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1

  # If a client wishes to use https for unauthenticated operations, that's
  # fine too.
  ssl_context.verify_mode = ssl.CERT_OPTIONAL
295 296 297 298 299 300 301
  # Note: python's standard ssl module does not provide a way to replace the
  # current CRL file on an existing openssl context: load_verify_locations ends
  # up calling X509_STORE_add_crl, which either adds the CRL to its list of
  # files or rejects the file. So either memory usage with increase until
  # context gets renewed, or we get stuck with an old CRL. So expect wsgi
  # application to implement these checks on its own when accessing client's
  # certificate.
Vincent Pelletier's avatar
Vincent Pelletier committed
302 303
  #ssl_context.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF
  ssl_context.load_verify_locations(
304
    cadata=utils.toUnicode(cau.getCACertificate()),
Vincent Pelletier's avatar
Vincent Pelletier committed
305
  )
306
  http_cas_certificate_list = http_cas.getCACertificateList()
Vincent Pelletier's avatar
Vincent Pelletier committed
307
  threshold_delta = datetime.timedelta(threshold, 0)
308 309 310 311 312 313 314 315 316 317 318 319
  exists = os.path.exists(server_key_path)
  if exists:
    try:
      old_crt_pem = utils.getLeafCertificate(server_key_path)
      old_crt = utils.load_certificate(
        old_crt_pem,
        http_cas_certificate_list,
        None,
      )
    except Exception: # pylint: disable=broad-except
      exists = False
  if exists:
320 321 322
    if renew or (
      old_crt.not_valid_after - threshold_delta < datetime.datetime.utcnow()
    ):
Vincent Pelletier's avatar
Vincent Pelletier committed
323 324
      new_key = utils.generatePrivateKey(key_len)
      new_key_pem = utils.dump_privatekey(new_key)
325
      new_crt_pem = http_cas.renew(
Vincent Pelletier's avatar
Vincent Pelletier committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339
        crt_pem=old_crt_pem,
        csr_pem=utils.dump_certificate_request(
          x509.CertificateSigningRequestBuilder(
          ).subject_name(
            # Note: caucase server ignores this, but cryptography
            # requires CSRs to have a subject.
            old_crt.subject,
          ).sign(
            private_key=new_key,
            algorithm=utils.DEFAULT_DIGEST_CLASS(),
            backend=_cryptography_backend,
          ),
        ),
      )
340
      new_ca_crt_pem = http_cas.getCACertificate()
341
      with _createKey(server_key_path) as crt_file:
Vincent Pelletier's avatar
Vincent Pelletier committed
342 343
        crt_file.write(new_key_pem)
        crt_file.write(new_crt_pem)
344
        crt_file.write(new_ca_crt_pem)
Vincent Pelletier's avatar
Vincent Pelletier committed
345 346
  else:
    new_key = utils.generatePrivateKey(key_len)
347
    csr_id = http_cas.appendCertificateSigningRequest(
Vincent Pelletier's avatar
Vincent Pelletier committed
348 349
      csr_pem=utils.dump_certificate_request(
        x509.CertificateSigningRequestBuilder(
350
          subject_name=x509.Name([
Vincent Pelletier's avatar
Vincent Pelletier committed
351
            x509.NameAttribute(
352
              oid=x509.oid.NameOID.ORGANIZATIONAL_UNIT_NAME,
353
              value=hostname_dnsname,
Vincent Pelletier's avatar
Vincent Pelletier committed
354 355
            ),
          ]),
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
          extensions=[
            Extension(
              x509.KeyUsage(
                # pylint: disable=bad-whitespace
                digital_signature =True,
                content_commitment=False,
                key_encipherment  =True,
                data_encipherment =False,
                key_agreement     =False,
                key_cert_sign     =False,
                crl_sign          =False,
                encipher_only     =False,
                decipher_only     =False,
                # pylint: enable=bad-whitespace
              ),
              critical=True,
            ),
            Extension(
              x509.SubjectAlternativeName([
375
                x509.DNSName(hostname_dnsname)
376 377
                if hostname_ip_address is None else
                x509.IPAddress(hostname_ip_address)
378 379 380 381
              ]),
              critical=True,
            ),
          ],
Vincent Pelletier's avatar
Vincent Pelletier committed
382 383 384 385 386 387 388 389
        ).sign(
          private_key=new_key,
          algorithm=utils.DEFAULT_DIGEST_CLASS(),
          backend=_cryptography_backend,
        ),
      ),
      override_limits=True,
    )
390 391
    http_cas.createCertificate(csr_id)
    new_crt_pem = http_cas.getCertificate(csr_id)
Vincent Pelletier's avatar
Vincent Pelletier committed
392
    new_key_pem = utils.dump_privatekey(new_key)
393
    new_ca_crt_pem = http_cas.getCACertificate()
394 395 396
    with _createKey(server_key_path) as crt_file:
      crt_file.write(new_key_pem)
      crt_file.write(new_crt_pem)
397
      crt_file.write(new_ca_crt_pem)
Vincent Pelletier's avatar
Vincent Pelletier committed
398
  ssl_context.load_cert_chain(server_key_path)
399 400 401
  return (
    ssl_context,
    utils.load_certificate(
402 403
      utils.getLeafCertificate(server_key_path),
      http_cas_certificate_list,
404 405 406
      None,
    ).not_valid_after - threshold_delta,
  )
Vincent Pelletier's avatar
Vincent Pelletier committed
407

Vincent Pelletier's avatar
Vincent Pelletier committed
408 409 410 411 412 413
def main(
  argv=None,
  until=utils.until,
  log_file=sys.stdout,
  error_file=sys.stderr,
):
Vincent Pelletier's avatar
Vincent Pelletier committed
414 415 416
  """
  Caucase stand-alone http server.
  """
417 418
  parser = argparse.ArgumentParser(
    description='caucased',
419 420 421 422
  )
  parser.add_argument(
    '--version',
    action='version',
423 424
    version=version.__version__,
  )
Vincent Pelletier's avatar
Vincent Pelletier committed
425 426 427 428 429 430 431 432 433 434 435 436
  parser.add_argument(
    '--db',
    default='caucase.sqlite',
    help='Path to the SQLite database. default: %(default)s',
  )
  parser.add_argument(
    '--server-key',
    default='server.key.pem',
    metavar='KEY_PATH',
    help='Path to the ssl key pair to use for https socket. '
    'default: %(default)s',
  )
437 438 439 440 441 442 443 444 445 446 447 448 449
  parser.add_argument(
    '--cors-key-store',
    default='cors.key',
    metavar='PATH',
    help='Path to a file containing CORS token keys. default: %(default)s',
  )
  parser.add_argument(
    '--cors-whitelist',
    default=[],
    nargs='+',
    metavar='URL',
    help='Origin values to always trust. default: none'
  )
Vincent Pelletier's avatar
Vincent Pelletier committed
450 451 452
  parser.add_argument(
    '--netloc',
    required=True,
453 454 455 456
    help='<host>[:<port>] at which certificate verificators may reach this '
    'service. This value is embedded in generated certificates (as CRL '
    'distribution point, as CA certificate common name, possibly more). '
    'See --base-port for how https port is derived from this port. '
Vincent Pelletier's avatar
Vincent Pelletier committed
457 458 459
    'Note on encoding: only ascii is currently supported. Non-ascii may be '
    'provided idna-encoded.',
  )
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
  parser.add_argument(
    '--base-port',
    type=int,
    help='Port at which caucase locally binds to provide HTTP service. '
    'If this port is 80, HTTPS service is provided on port 443, otherwise '
    'it is provided on --base-port + 1. '
    'If derived HTTPS port is not available, caucase will exit with an error '
    'status. default: --netloc\'s port, or 80',
  )
  parser.add_argument(
    '--bind',
    default=[],
    action='append',
    help='Address on which caucase locally binds. '
    'default: addresses --netloc\'s <host> resolves into.',
  )
Vincent Pelletier's avatar
Vincent Pelletier committed
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
  parser.add_argument(
    '--threshold',
    default=31,
    type=float,
    help='The remaining certificate validity period, in days, under '
    'which a renew is desired. default: %(default)s',
  )
  parser.add_argument(
    '--key-len',
    default=2048,
    type=int,
    metavar='BITLENGTH',
    help='Number of bits to use when generating a new private key. '
    'default: %(default)s',
  )

  service_group = parser.add_argument_group(
    'CAS options: normal certificates, which are not given any privilege on '
    'caucased',
  )

  user_group = parser.add_argument_group(
    'CAU options: special certificates, which are allowed to sign other '
    'certificates and can decrypt backups',
  )

  service_group.add_argument(
    '--service-crt-validity',
    default=3 * 31,
    type=float,
    metavar='DAYS',
    help='Number of days an issued certificate is valid for. '
    'default: %(default)s',
  )
  user_group.add_argument(
    '--user-crt-validity',
    default=3 * 31,
    type=float,
    metavar='DAYS',
    help='Number of days an issued certificate is valid for. '
    'default: %(default)s',
  )

  service_group.add_argument(
    '--service-max-csr',
    default=50,
    type=int,
    help='Maximum number of pending CSR. Further CSR get refused until '
    'an existing ones gets signed or rejected. default: %(default)s',
  )
  user_group.add_argument(
    '--user-max-csr',
    default=50,
    type=int,
    help='Maximum number of pending CSR. Further CSR get refused until '
    'an existing ones gets signed or rejected. default: %(default)s',
  )

  service_group.add_argument(
    '--service-auto-approve-count',
    default=0,
    type=int,
    metavar='COUNT',
    help='Number service certificates which should be automatically signed on '
    'submission, excluding the one needed to serve caucase. '
    'default: %(default)s'
  )
  user_group.add_argument(
    '--user-auto-approve-count',
    default=1,
    type=int,
    metavar='COUNT',
    help='Number of user certificates which should be automatically signed on '
    'submission. default: %(default)s',
  )
  parser.add_argument(
    '--lock-auto-approve-count',
    action='store_true',
    help='The first time this option is given, --service-auto-approve-count '
    'and --user-auto-approve-count values are stored inside caucase database '
    'and will not be altered by further invocations. Once the respective '
    'certificate issuance counters reach these values, no further '
    'certificates will be ever automatically signed.'
  )

  backup_group = parser.add_argument_group(
    'Backup options',
  )
  backup_group.add_argument(
    '--backup-directory',
566
    help='Backup directory path. Backups will be periodically stored in '
567 568 569 570
    'given directory, encrypted with all user certificates which are valid '
    'at backup generation time. Any one of the associated private keys can '
    'decypher it. If not set or no user certificate exists, no backup will '
    'be created.',
Vincent Pelletier's avatar
Vincent Pelletier committed
571 572 573 574 575 576 577 578 579
  )
  backup_group.add_argument(
    '--backup-period',
    default=1,
    type=float,
    help='Number of days between backups. default: %(default)s'
  )
  args = parser.parse_args(argv)

580
  base_url = u'http://' + utils.toUnicode(args.netloc)
Vincent Pelletier's avatar
Vincent Pelletier committed
581 582
  parsed_base_url = urlparse(base_url)
  hostname = parsed_base_url.hostname
583 584
  name_constraints_permited = []
  name_constraints_excluded = []
585
  hostname_dnsname = utils.toUnicode(hostname)
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
  try:
    hostname_ip_address = ipaddress.ip_address(hostname_dnsname)
  except ValueError:
    # Hostname is not an ip address, it must be a hostname
    name_constraints_permited.append(
      x509.DNSName(hostname_dnsname),
    )
    hostname_ip_address = None
  else:
    # Hostname is an ip address, forbid hostname claims.
    name_constraints_excluded.append(
      x509.DNSName(u''),
    )
    # Convert to a network to meet NameConstraint restrictions.
    # Resulting network has maximal prefix length, so it really just covers
    # one IP.
    name_constraints_permited.append(
      x509.IPAddress(ipaddress.ip_network(hostname_ip_address)),
    )

606 607 608 609 610
  http_port = (
    parsed_base_url.port
    if args.base_port is None
    else args.base_port
  )
611
  https_port = 443 if http_port == 80 else http_port + 1
Vincent Pelletier's avatar
Vincent Pelletier committed
612
  cau_crt_life_time = args.user_crt_validity
613 614
  # Certificate Authority for Users: emitted certificate are trusted by this
  # service.
Vincent Pelletier's avatar
Vincent Pelletier committed
615 616 617
  cau = UserCertificateAuthority(
    storage=SQLite3Storage(
      db_path=args.db,
618 619
      table_prefix='cau',
      max_csr_amount=args.user_max_csr,
Vincent Pelletier's avatar
Vincent Pelletier committed
620
      # Effectively disables certificate pruning
621 622 623
      crt_keep_time=cau_crt_life_time,
      crt_read_keep_time=cau_crt_life_time,
      enforce_unique_key_id=True,
Vincent Pelletier's avatar
Vincent Pelletier committed
624
    ),
625 626 627 628 629 630 631 632 633
    ca_subject_dict={
      'CN': u'Caucase CAU' + (
        u'' if base_url is None else u' at ' + base_url + '/cau'
      ),
    },
    ca_key_size=args.key_len,
    crt_life_time=cau_crt_life_time,
    auto_sign_csr_amount=args.user_auto_approve_count,
    lock_auto_sign_csr_amount=args.lock_auto_approve_count,
Vincent Pelletier's avatar
Vincent Pelletier committed
634
  )
635 636
  # Certificate Authority for Services: server and client certificates, the
  # final produce of caucase.
Vincent Pelletier's avatar
Vincent Pelletier committed
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
  cas = CertificateAuthority(
    storage=SQLite3Storage(
      db_path=args.db,
      table_prefix='cas',
      max_csr_amount=args.service_max_csr,
    ),
    ca_subject_dict={
      'CN': u'Caucase CAS' + (
        u'' if base_url is None else u' at ' + base_url + '/cas'
      ),
    },
    crl_base_url=None if base_url is None else base_url + u'/cas/crl',
    ca_key_size=args.key_len,
    crt_life_time=args.service_crt_validity,
    auto_sign_csr_amount=args.service_auto_approve_count,
    lock_auto_sign_csr_amount=args.lock_auto_approve_count,
  )
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
  # Certificate Authority for caucased https service. Distinct from CAS to be
  # able to restrict the validity scope of produced CA certificate, so that it
  # can be trusted by genral-purpose https clients without introducing the risk
  # of producing rogue certificates.
  # This Certificate Authority is only internal to this service, and not exposed
  # to http(s), as it can and must only be used to caucased https certificate
  # signature. Only the CA certificate is exposed, to allow verification.
  https_base_url = urlunsplit((
    'https',
    '[' + hostname + ']:' + str(https_port),
    '/',
    None,
    None,
  ))
  http_cas = CertificateAuthority(
    storage=SQLite3Storage(
      db_path=args.db,
      table_prefix='http_cas',
    ),
    ca_subject_dict={
      'CN': u'Caucased CA at ' + https_base_url,
    },
676 677 678 679 680 681 682 683 684
    ca_extension_list=[
      Extension(
        x509.NameConstraints(
          permitted_subtrees=name_constraints_permited,
          excluded_subtrees=name_constraints_excluded or None,
        ),
        critical=True,
      ),
    ],
685 686 687 688 689 690 691 692 693
    ca_key_size=args.key_len,
    # This CA certificate will be installed in browser key stores, where
    # automated renewal will be unlikely to happen. As this CA certificate
    # will only sign caucased https certificates for this process, assume
    # very little will leak from the private key with each signed certificate.
    # So it should be safe and more practical to give it a long life.
    ca_life_period=40, # approx. 10 years
    crt_life_time=args.service_crt_validity,
  )
694
  if os.path.exists(args.cors_key_store):
695
    with open(args.cors_key_store, 'rb') as cors_key_file:
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
      cors_secret_list = json.load(cors_key_file)
  else:
    cors_secret_list = []
  def saveCORSKeyList(cors_secret_list):
    """
    Update CORS key store when a new key was generated.
    """
    with _createKey(args.cors_key_store) as cors_key_file:
      json.dump(cors_secret_list, cors_key_file)
  application = Application(
    cau=cau,
    cas=cas,
    http_url=urlunsplit((
      'http',
      '[' + hostname + ']:' + str(http_port),
      '/',
      None,
      None,
    )),
    https_url=https_base_url,
    cors_token_manager=CORSTokenManager(
      secret_list=cors_secret_list,
      onNewKey=saveCORSKeyList,
    ),
    cors_whitelist=args.cors_whitelist,
  )
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
  http_list = []
  https_list = []
  known_host_set = set()
  for bind in args.bind or [hostname]:
    for family, _, _, _, sockaddr in socket.getaddrinfo(
      bind,
      0,
      socket.AF_UNSPEC,
      socket.SOCK_STREAM,
      socket.IPPROTO_TCP,
    ):
      if family == socket.AF_INET:
        host, _ = sockaddr
      elif family == socket.AF_INET6:
        host, _, _, _ = sockaddr
      else:
        continue
      if host in known_host_set:
        continue
      known_host_set.add(host)
742 743
      print(
        'Listening on [%s]:%i-%i' % (
744 745 746 747
          host,
          http_port,
          https_port,
        ),
Vincent Pelletier's avatar
Vincent Pelletier committed
748
        file=error_file,
749 750 751 752 753 754
      )
      http_list.append(
        make_server(
          host=host,
          port=http_port,
          app=application,
Vincent Pelletier's avatar
Vincent Pelletier committed
755 756 757 758 759 760 761 762 763
          server_class=partial(
            ThreadingWSGIServer,
            error_file=error_file,
          ),
          handler_class=partial(
            CaucaseWSGIRequestHandler,
            log_file=log_file,
            error_file=error_file,
          ),
764 765 766 767 768 769 770
        ),
      )
      https_list.append(
        make_server(
          host=host,
          port=https_port,
          app=application,
Vincent Pelletier's avatar
Vincent Pelletier committed
771 772 773 774 775 776 777 778 779
          server_class=partial(
            ThreadingWSGIServer,
            error_file=error_file,
          ),
          handler_class=partial(
            CaucaseSSLWSGIRequestHandler,
            log_file=log_file,
            error_file=error_file,
          ),
780 781 782
        ),
      )
  ssl_context, next_ssl_update = getSSLContext(
Vincent Pelletier's avatar
Vincent Pelletier committed
783 784 785
    key_len=args.key_len,
    threshold=args.threshold,
    server_key_path=args.server_key,
786 787
    hostname_ip_address=hostname_ip_address,
    hostname_dnsname=hostname_dnsname,
Vincent Pelletier's avatar
Vincent Pelletier committed
788
    cau=cau,
789
    http_cas=http_cas,
Vincent Pelletier's avatar
Vincent Pelletier committed
790
  )
791 792 793 794 795 796
  next_deadline = next_ssl_update
  for https in https_list:
    https.socket = ssl_context.wrap_socket(
      sock=https.socket,
      server_side=True,
    )
Vincent Pelletier's avatar
Vincent Pelletier committed
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
  if args.backup_directory:
    backup_period = datetime.timedelta(args.backup_period, 0)
    try:
      next_backup = max(
        datetime.datetime.utcfromtimestamp(os.stat(x).st_ctime)
        for x in glob.iglob(
          os.path.join(args.backup_directory, '*' + BACKUP_SUFFIX),
        )
      ) + backup_period
    except ValueError:
      next_backup = datetime.datetime.utcnow()
    next_deadline = min(
      next_deadline,
      next_backup,
    )
  else:
    next_backup = None
814
  for server in itertools.chain(http_list, https_list):
815 816 817 818 819 820
    try:
      server.server_bind()
      server.server_activate()
    except:
      server.server_close()
      raise
821
    startServerThread(server)
Vincent Pelletier's avatar
Vincent Pelletier committed
822 823
  try:
    while True:
824
      now = until(next_deadline)
Vincent Pelletier's avatar
Vincent Pelletier committed
825
      if now >= next_ssl_update:
826
        ssl_context, next_ssl_update = getSSLContext(
Vincent Pelletier's avatar
Vincent Pelletier committed
827 828 829
          key_len=args.key_len,
          threshold=args.threshold,
          server_key_path=args.server_key,
830 831
          hostname_ip_address=hostname_ip_address,
          hostname_dnsname=hostname_dnsname,
Vincent Pelletier's avatar
Vincent Pelletier committed
832
          cau=cau,
833
          http_cas=http_cas,
834
          renew=True,
Vincent Pelletier's avatar
Vincent Pelletier committed
835
        )
836
        for https in https_list:
837 838 839 840 841 842 843 844 845 846 847 848
          ssl_socket = https.socket
          try:
            ssl_socket.context = ssl_context
          except AttributeError:
            # Workaround for python bug 34747: changing a listening
            # SSLSocket's SSL context fails on
            # "self._sslobj.context = context" while "self._sslobj" is only
            # set on connected sockets.
            # Luckily is it done just after updating "self._context" which is
            # what is actually used when accepting a connection - so the update
            # is actually successful.
            pass
Vincent Pelletier's avatar
Vincent Pelletier committed
849 850 851 852 853 854 855
      if next_backup is None:
        next_deadline = next_ssl_update
      else:
        if now >= next_backup:
          tmp_backup_fd, tmp_backup_path = tempfile.mkstemp(
            prefix='caucase_backup_',
          )
856
          with os.fdopen(tmp_backup_fd, 'wb') as backup_file:
Vincent Pelletier's avatar
Vincent Pelletier committed
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
            result = cau.doBackup(backup_file.write)
          if result:
            backup_path = os.path.join(
              args.backup_directory,
              now.strftime('%Y%m%d%H%M%S') + BACKUP_SUFFIX,
            )
            os.rename(tmp_backup_path, backup_path)
            next_backup = now + backup_period
          else:
            os.unlink(tmp_backup_path)
            next_backup = now + datetime.timedelta(0, 3600)
        next_deadline = min(
          next_ssl_update,
          next_backup,
        )
  except utils.SleepInterrupt:
    pass
874
  finally:
Vincent Pelletier's avatar
Vincent Pelletier committed
875
    print('Exiting', file=error_file)
876
    for server in itertools.chain(http_list, https_list):
877
      server.server_close()
878
      server.shutdown()
879 880 881 882 883 884 885

def manage(argv=None):
  """
  caucased database management tool.
  """
  parser = argparse.ArgumentParser(
    description='caucased caucased database management tool',
886 887 888 889
  )
  parser.add_argument(
    '--version',
    action='version',
890
    version=version.__version__,
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
  )
  parser.add_argument(
    '--db',
    default='caucase.sqlite',
    help='Path to the SQLite database. default: %(default)s',
  )
  parser.add_argument(
    '--user-crt-validity',
    default=3 * 31,
    type=float,
    metavar='DAYS',
    help='Number of days an issued certificate is valid for. Useful with '
    '--restore-backup as a new user certificate must be produced. '
    'default: %(default)s',
  )

  parser.add_argument(
    '--restore-backup',
    nargs=4,
    metavar=('BACKUP_PATH', 'KEY_PATH', 'CSR_PATH', 'CRT_PATH'),
    help='Restore the file at BACKUP_PATH, decyphering it with the key '
    'at KEY_PATH, revoking corresponding certificate and issuing a new '
    'one in CRT_PATH using the public key in CSR_PATH. '
    'Fails if database exists.',
  )
  parser.add_argument(
    '--import-ca',
    default=[],
    metavar='PEM_FILE',
    action='append',
921
    type=argparse.FileType('rb'),
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
    help='Import key pairs as initial service CA certificate. '
    'May be provided multiple times to import multiple key pairs. '
    'Keys and certificates may be in separate files. '
    'If there are multiple keys or certificates, all will be imported. '
    'Will fail if there is any certificate without a key, or vice-versa, '
    'or if any certificate is not suitable for use as a CA certificate. '
    'Caucase-initiated CA renewal, which will happen when latest provided '
    'has less than 3 times --service-crt-validity validity period left, '
    'will copy that CA\'s extensions to produce the new certificate. '
    'Passphrase will be prompted for each protected key.',
  )
  parser.add_argument(
    '--import-bad-ca',
    action='store_true',
    default=False,
    help='Do not check sanity of imported CA certificates. Useful when '
    'migrating a custom CA where clients do very customised checks. Do not '
    'use this unless you are certain you need it and it is safe for your '
    'use-case.',
  )
942 943 944 945 946
  parser.add_argument(
    '--import-crl',
    default=[],
    metavar='PEM_FILE',
    action='append',
947
    type=argparse.FileType('rb'),
948 949 950 951
    help='Import service revocation list. Corresponding CA certificate must '
    'be already present in the database (including added in the same run '
    'using --import-ca).',
  )
952 953 954
  parser.add_argument(
    '--export-ca',
    metavar='PEM_FILE',
955
    type=argparse.FileType('wb'),
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
    help='Export all CA certificates in a PEM file. Passphrase will be '
    'prompted to protect all keys.',
  )
  args = parser.parse_args(argv)
  db_path = args.db
  if args.restore_backup:
    (
      backup_path,
      backup_key_path,
      backup_csr_path,
      backup_crt_path,
    ) = args.restore_backup
    try:
      _, key_pem, _ = utils.getKeyPair(backup_key_path)
    except ValueError:
      # maybe user extracted their private key ?
      key_pem = utils.getKey(backup_key_path)
    cau_crt_life_time = args.user_crt_validity
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
    with open(
      backup_path,
      'rb',
    ) as backup_file, open(
      backup_crt_path,
      'ab',
    ) as new_crt_file:
      new_crt_file.write(
        UserCertificateAuthority.restoreBackup(
          db_class=SQLite3Storage,
          db_path=db_path,
          read=backup_file.read,
          key_pem=key_pem,
          csr_pem=utils.getCertRequest(backup_csr_path),
          db_kw={
            'table_prefix': 'cau',
            # max_csr_amount: not needed, renewal ignores quota
            # Effectively disables certificate expiration
            'crt_keep_time': cau_crt_life_time,
            'crt_read_keep_time': cau_crt_life_time,
            'enforce_unique_key_id': True,
          },
          kw={
            # Disable CA cert renewal
            'ca_key_size': None,
            'crt_life_time': cau_crt_life_time,
          },
        ),
      )
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
  if args.import_ca:
    import_ca_dict = defaultdict(
      (lambda: {'crt': None, 'key': None, 'from': []}),
    )
    for ca_file in args.import_ca:
      for index, component in enumerate(pem.parse(ca_file.read())):
        name = '%r, block %i' % (ca_file.name, index)
        if isinstance(component, pem.Certificate):
          component_name = 'crt'
          component_value = x509.load_pem_x509_certificate(
            component.as_bytes(),
            _cryptography_backend,
          )
        elif isinstance(component, pem.Key):
          password = None
          while True:
            component_name = 'key'
            try:
              component_value = serialization.load_pem_private_key(
                component.as_bytes(),
                password,
                _cryptography_backend,
              )
            except TypeError:
              password = getBytePass('Passphrase for key at %s: ' % (name, ))
            else:
              break
        else:
          raise TypeError('%s is of unsupported type %r' % (
            name,
            type(component),
          ))
        import_ca = import_ca_dict[
          x509.SubjectKeyIdentifier.from_public_key(
            component_value.public_key(),
          ).digest
        ]
        import_ca[component_name] = component_value
        import_ca['from'].append(name)
    now = utils.datetime2timestamp(datetime.datetime.utcnow())
    imported = 0
    cas_db = SQLite3Storage(
      db_path,
      table_prefix='cas',
    )
    for identifier, ca_pair in import_ca_dict.iteritems():
      found_from = ', '.join(ca_pair['from'])
      crt = ca_pair['crt']
      if crt is None:
1052
        print(b'No certificate correspond to', found_from, b'- skipping')
1053 1054 1055
        continue
      expiration = utils.datetime2timestamp(crt.not_valid_after)
      if expiration < now:
1056
        print(b'Skipping expired certificate from', found_from)
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
        del import_ca_dict[identifier]
        continue
      if not args.import_bad_ca:
        try:
          basic_contraints = crt.extensions.get_extension_for_class(
            x509.BasicConstraints,
          )
          key_usage = crt.extensions.get_extension_for_class(
            x509.KeyUsage,
          ).value
        except x509.ExtensionNotFound:
          failed = True
        else:
          failed = (
            not basic_contraints.value.ca or not basic_contraints.critical
            or not key_usage.key_cert_sign or not key_usage.crl_sign
          )
        if failed:
1075
          print(b'Skipping non-CA certificate from', found_from)
1076 1077 1078
          continue
      key = ca_pair['key']
      if key is None:
1079
        print(b'No private key correspond to', found_from, b'- skipping')
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
        continue
      imported += 1
      cas_db.appendCAKeyPair(
        expiration,
        {
          'key_pem': utils.dump_privatekey(key),
          'crt_pem': utils.dump_certificate(crt),
        },
      )
    if not imported:
      raise ValueError('No CA certificate imported')
1091
    print(b'Imported %i CA certificates' % imported)
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
  if args.import_crl:
    db = SQLite3Storage(db_path, table_prefix='cas')
    trusted_ca_crt_set = [
      utils.load_ca_certificate(x['crt_pem'])
      for x in db.getCAKeyPairList()
    ]
    latest_ca_not_after = max(
      x.not_valid_after
      for x in trusted_ca_crt_set
    )
    already_revoked_count = revoked_count = 0
    for crl_file in args.import_crl:
      for revoked in utils.load_crl(crl_file.read(), trusted_ca_crt_set):
        try:
          db.revoke(
            revoked.serial_number,
            latest_ca_not_after,
          )
        except exceptions.Found:
          already_revoked_count += 1
        else:
          revoked_count += 1
1114
    print(b'Revoked %i certificates (%i were already revoked)' % (
1115 1116 1117
      revoked_count,
      already_revoked_count,
    ))
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
  if args.export_ca is not None:
    encryption_algorithm = serialization.BestAvailableEncryption(
      getBytePass('CA export passphrase: ')
    )
    write = args.export_ca.write
    for key_pair in SQLite3Storage(
      db_path,
      table_prefix='cas',
    ).getCAKeyPairList():
      write(
        key_pair['crt_pem'] + serialization.load_pem_private_key(
          key_pair['key_pem'],
          None,
          _cryptography_backend,
        ).private_bytes(
          encoding=serialization.Encoding.PEM,
          format=serialization.PrivateFormat.TraditionalOpenSSL,
          encryption_algorithm=encryption_algorithm,
        ),
      )
    args.export_ca.close()