test.py 119 KB
Newer Older
Vincent Pelletier's avatar
Vincent Pelletier committed
1
# This file is part of caucase
2
# Copyright (C) 2017-2021  Nexedi SA
Vincent Pelletier's avatar
Vincent Pelletier committed
3 4 5
#     Alain Takoudjou <alain.takoudjou@nexedi.com>
#     Vincent Pelletier <vincent@nexedi.com>
#
6 7 8
# This program is free software: you can Use, Study, Modify and Redistribute
# it under the terms of the GNU General Public License version 3, or (at your
# option) any later version, as published by the Free Software Foundation.
Vincent Pelletier's avatar
Vincent Pelletier committed
9
#
10 11 12 13 14
# You can also Link and Combine this program with other software covered by
# the terms of any of the Free Software licenses or any of the Open Source
# Initiative approved licenses and Convey the resulting work. Corresponding
# source of such a combination shall include the source code for all other
# software used.
Vincent Pelletier's avatar
Vincent Pelletier committed
15
#
16 17 18 19 20
# This program is distributed WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See COPYING file for full licensing terms.
# See https://www.nexedi.com/licensing for rationale and options.
Vincent Pelletier's avatar
Vincent Pelletier committed
21 22 23 24 25
"""
Caucase - Certificate Authority for Users, Certificate Authority for SErvices

Test suite
"""
26
# pylint: disable=too-many-lines, too-many-public-methods
Vincent Pelletier's avatar
Vincent Pelletier committed
27
from __future__ import absolute_import
28 29 30 31 32
try:
  from http.cookies import SimpleCookie
except ImportError: # pragma: no cover
  # BBB: py2.7
  from Cookie import SimpleCookie
Vincent Pelletier's avatar
Vincent Pelletier committed
33
import datetime
34 35 36
# pylint: disable=no-name-in-module, import-error
from distutils.spawn import find_executable
# pylint: enable=no-name-in-module, import-error
Vincent Pelletier's avatar
Vincent Pelletier committed
37
import errno
Vincent Pelletier's avatar
Vincent Pelletier committed
38
import functools
Vincent Pelletier's avatar
Vincent Pelletier committed
39
import glob
40 41 42 43 44 45 46
try: # pragma: no cover
  import html.parser as html_parser
  import http.client as http_client
except ImportError: # pragma: no cover
  # BBB: py2.7
  import HTMLParser as html_parser
  import httplib as http_client
47
from io import BytesIO, StringIO
Vincent Pelletier's avatar
Vincent Pelletier committed
48
import ipaddress
49
import json
Vincent Pelletier's avatar
Vincent Pelletier committed
50 51
import os
import random
52
import re
Vincent Pelletier's avatar
Vincent Pelletier committed
53 54 55
import shutil
import socket
import sqlite3
56
import ssl
57
import subprocess
Vincent Pelletier's avatar
Vincent Pelletier committed
58
import sys
59
import tarfile
Vincent Pelletier's avatar
Vincent Pelletier committed
60
import tempfile
61
import threading
Vincent Pelletier's avatar
Vincent Pelletier committed
62
import time
Vincent Pelletier's avatar
Vincent Pelletier committed
63
import unittest
64 65 66 67 68 69 70
try: # pragma: no cover
  from urllib.parse import quote, urlencode
  import urllib.parse as urllib_parse
except ImportError: # pragma: no cover
  # BBB: py2.7
  from urllib import quote, urlencode
  import urlparse as urllib_parse
Vincent Pelletier's avatar
Vincent Pelletier committed
71
from cryptography import x509
72
import cryptography.exceptions
Vincent Pelletier's avatar
Vincent Pelletier committed
73
from cryptography.hazmat.backends import default_backend
74
from cryptography.hazmat.primitives import serialization, hashes
Vincent Pelletier's avatar
Vincent Pelletier committed
75
from caucase import cli
76
import caucase.ca
77
from caucase.ca import Extension, CertificateAuthority
78
from caucase.client import CaucaseError, CaucaseClient
79
from caucase.exceptions import CertificateVerificationError
80 81 82
# Do not import caucase.http into this namespace: 2to3 will import standard
# http module, which will then be masqued by caucase's http submodule.
import caucase.http
Vincent Pelletier's avatar
Vincent Pelletier committed
83 84 85 86 87 88 89
from caucase import utils
from caucase import exceptions
from caucase import wsgi
from caucase.storage import SQLite3Storage

_cryptography_backend = default_backend()

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
def _getTestOID():
  """
  Some cryptography versions do not tolerate large OIDs. Detect these here.
  """
  LONG_UUID = 285541874270823339875695650038637483518
  LONG_OID = '2.25.%i' % (LONG_UUID, )
  # XXX: this is not a compliant use of the 2.25 OID subtree
  SHORT_OID = '2.25.%i' % (LONG_UUID & (2**28 - 1), )
  test_private_key = utils.generatePrivateKey(key_len=2048)
  def makeAndLoadCSR(oid):
    """
    Make a CSR with a policy extension for given OID.
    """
    extension = x509.CertificatePolicies([
      x509.PolicyInformation(
        x509.oid.ObjectIdentifier(oid),
        None,
      )
    ])
    csr_pem = utils.dump_certificate_request(
      x509.CertificateSigningRequestBuilder(
        subject_name=x509.Name([
          x509.NameAttribute(oid=x509.oid.NameOID.COMMON_NAME, value=u'test'),
        ]),
      ).add_extension(
        extension,
        critical=False,
      ).sign(
        private_key=test_private_key,
        algorithm=utils.DEFAULT_DIGEST_CLASS(),
        backend=_cryptography_backend,
      )
    )
    # cryptography may succeed in serialising the CSR, but may fail when
    # loading it and accessing extensions.
    _ = x509.load_pem_x509_csr(
      csr_pem,
      _cryptography_backend,
    ).extensions.get_extension_for_class(
      extension.__class__,
    )
  # sanity check
  makeAndLoadCSR(SHORT_OID)
  try:
    # actual verification
    makeAndLoadCSR(LONG_OID)
  except ValueError: # pragma: no cover
    return (False, SHORT_OID)
  return (True, LONG_OID) # pragma: no cover
(
  _HAS_LONG_OID_SUPPORT,
  NOT_CAUCASE_OID,
) = _getTestOID()
del _getTestOID
144 145
A_YEAR_IN_SECONDS = 60 * 60 * 24 * 365 # Roughly a year

146 147 148 149 150 151 152 153 154 155 156 157 158
if sys.version_info[0] >= 3: # pragma: no cover
  TestCase = unittest.TestCase
else: # pragma: no cover
  # BBB: py2.7
  class TestCase(unittest.TestCase):
    """
    For forward-compatibility wit 3.x unittest API.
    """
    assertRegex = unittest.TestCase.assertRegexpMatches

class assertHTMLNoScriptAlert(
  html_parser.HTMLParser,
): # pylint: disable=abstract-method
159 160 161 162 163 164
  """
  Raise AssertionError if it finds a <script> tag containing "alert".
  """
  _in_script = False

  def __init__(self, data):
165
    html_parser.HTMLParser.__init__(self)
166 167 168 169 170 171 172
    self.feed(data)
    self.close()

  def reset(self):
    """
    Out of script tag.
    """
173
    html_parser.HTMLParser.reset(self)
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    self._in_script = False

  def handle_starttag(self, tag, attrs):
    """
    Update whether a script tag was entered.
    """
    assert not self._in_script
    self._in_script = tag == 'script'

  def handle_endtag(self, tag): # pragma: no cover
    """
    Track leaving script tag.
    """
    if tag == 'script':
      assert self._in_script
      self._in_script = False

  def handle_data(self, data):
    """
    Check script tag content.
    """
    assert not self._in_script or 'alert' not in data, (
      '<script>...alert...</script> found'
    )
Vincent Pelletier's avatar
Vincent Pelletier committed
198

199
def canConnect(address): # pragma: no cover
Vincent Pelletier's avatar
Vincent Pelletier committed
200 201 202 203 204
  """
  Returns True if a connection can be established to given address, False
  otherwise.
  """
  try:
205
    sock = socket.create_connection(address)
206
  except socket.error as e:
Vincent Pelletier's avatar
Vincent Pelletier committed
207 208 209
    if e.errno == errno.ECONNREFUSED:
      return False
    raise
210 211
  else:
    sock.close()
Vincent Pelletier's avatar
Vincent Pelletier committed
212 213
  return True

214
def retry(callback, try_count=10, try_delay=0.1): # pragma: no cover
Vincent Pelletier's avatar
Vincent Pelletier committed
215 216 217 218 219
  """
  Poll <callback> every <try_delay> for <try_count> times or until it returns
  a true value.
  Always returns the value returned by latest callback invocation.
  """
220
  for _ in range(try_count):
Vincent Pelletier's avatar
Vincent Pelletier committed
221 222
    result = callback()
    if result:
223
      break
Vincent Pelletier's avatar
Vincent Pelletier committed
224
    time.sleep(try_delay)
225
  return result
Vincent Pelletier's avatar
Vincent Pelletier committed
226

227 228 229
class FakeStreamRequest(object):
  """
  For testing StreamRequestHandler subclasses
230
  (like caucase.http.CaucaseWSGIRequestHandler).
231 232 233 234 235 236 237 238 239 240 241 242 243 244
  """
  def __init__(self, rfile, wfile):
    """
    rfile & wfile: Both halves of emulated socket.
    """
    self._rfile = rfile
    self._wfile = wfile

  def makefile(self, mode, _):
    """
    Fake splitting the socket.
    """
    return self._rfile if 'r' in mode else self._wfile

245
  def sendall(self, data, flags=None): # pragma: no cover
246 247 248
    """
    Redirect sendall.
    """
249
    _ = flags # Silence pylint
250 251
    self._wfile.write(data)

252 253 254 255 256 257 258 259 260 261 262 263 264 265
class NoCloseFileProxy(object):
  """
  Intercept .close() calls, for example to allow reading StringIO content
  despite attempted closure.
  """
  def __init__(self, real_file):
    """
    real_file: Object toforward all non-close calls to.
    """
    self._real_file = real_file

  def __getattr__(self, name):
    return getattr(self._real_file, name)

266
  def close(self): # pragma: no cover
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    """
    Don't.
    """
    pass

class FakeAppServer(object):
  """
  Minimal fake WSGI app server.
  """
  def __init__(self, app):
    self._app = app
    self.base_environ = {}

  def get_app(self):
    """
    Retrieve app.
    """
    return self._app

286
class DummyApp(object):
287
  """
288
  Simple WSGI app with limited (but simple) scripting.
289
  """
290 291 292 293 294 295 296
  def __init__(self, callback=lambda x: []):
    """
    callback (callable)
      Received environ as argument,
      Expected to return response body as an iterable.
    """
    self._callback = callback
297

298 299 300 301 302 303
  def __call__(self, environ, start_response):
    """
    WSGI entry point
    """
    start_response('200 OK', [])
    return self._callback(environ)
304

305 306 307 308 309 310 311
ON_EVENT_RAISE = object()
ON_EVENT_EXPIRE = object()
class UntilEvent(object):
  """
  Like utils.until, but with a threading.Event replacing
  KeyboardInterrupt as the early interruption source.
  """
312
  def __init__(self, event, event_wait=10):
313 314 315 316 317
    """
    event (Event)
      Event to wait upon. Set and cleared outside this class.
    """
    self._event = event
318
    self._event_wait = event_wait
319 320 321
    self._action = ON_EVENT_RAISE
    self._wait_event = threading.Event()
    self._wait_event.clear()
322
    self._deadline = None
323 324 325 326 327 328

  @property
  def action(self):
    """
    Retrieve current action. Not very useful.
    """
329
    return self._action # pragma: no cover
330 331 332 333 334 335 336

  @action.setter
  def action(self, value):
    """
    Change the action which will happen on next event wakeup.
    """
    if value not in (ON_EVENT_RAISE, ON_EVENT_EXPIRE):
337
      raise ValueError # pragma: no cover
338 339
    self._action = value

340 341 342 343 344 345 346 347 348 349 350
  @property
  def deadline(self):
    """
    Retrieve the deadline parameter given to latest call.
    Only valid after a "wait" call returned successfully, and before wakeup
    event gets set.
    """
    result = self._deadline
    assert result is not None
    return result

351
  def wait(self, timeout=10):
352 353 354 355 356
    """
    Wait for event to be waited upon at least once.
    timeout (float)
      Maximum number of seconds to wait for.
    """
357 358 359
    if not self._wait_event.wait(timeout): # pragma: no cover
      raise AssertionError('Timeout reached')
    self._wait_event.clear()
360 361 362

  def __call__(self, deadline):
    """
363 364 365
    Sleep until event is set, then
    - if self.action is ON_EVENT_RAISE, raises utils.SleepInterrupt.
    - if self.action is ON_EVENT_EXPIRE, deadline time it returned.
366 367
    """
    now = datetime.datetime.utcnow()
368
    if now < deadline:
369
      self._deadline = deadline
370
      self._wait_event.set()
371
      assert self._event.wait(self._event_wait)
372
      self._deadline = None
373
      self._event.clear()
374 375 376 377 378 379
      if self._action is ON_EVENT_EXPIRE:
        now = deadline
      else:
        raise utils.SleepInterrupt
    return now

Vincent Pelletier's avatar
Vincent Pelletier committed
380 381 382 383 384 385 386 387 388 389 390 391
def print_buffer_on_error(func):
  """
  Write output buffer to stdout when wrapped method raises.
  func is expected to be a method from CaucaseTest class.
  """
  @functools.wraps(func)
  def wrapper(self, *args, **kw):
    """
    Write output buffer to stdout when wrapped method raises.
    """
    try:
      return func(self, *args, **kw)
392
    except Exception: # pragma: no cover
393 394 395 396 397
      stdout = utils.toUnicodeWritableStream(sys.stdout)
      stdout.write(os.linesep)
      stdout.write(
        self.caucase_test_output.getvalue().decode('ascii', 'replace'),
      )
Vincent Pelletier's avatar
Vincent Pelletier committed
398 399 400
      raise
  return wrapper

401
_clean_caucased_snapshot = None
402
class CaucaseTest(TestCase):
Vincent Pelletier's avatar
Vincent Pelletier committed
403 404 405 406 407 408 409 410 411 412 413
  """
  Test a complete caucase setup: spawn a caucase-http server on CAUCASE_NETLOC
  and use caucase-cli to access it.
  """
  _server = None

  def setUp(self):
    """
    Prepare test data directory and file paths, and start caucased as most
    tests will need to interact with it.
    """
414
    global _clean_caucased_snapshot # pylint: disable=global-statement
Vincent Pelletier's avatar
Vincent Pelletier committed
415 416 417 418 419
    self._data_dir = data_dir = tempfile.mkdtemp(prefix='caucase_test_')

    self._client_dir = client_dir = os.path.join(data_dir, 'client')
    os.mkdir(client_dir)
    self._client_ca_crt      = os.path.join(client_dir, 'cas.crt.pem')
420
    self._client_ca_dir      = os.path.join(client_dir, 'cas_crt')
Vincent Pelletier's avatar
Vincent Pelletier committed
421 422 423 424
    self._client_user_ca_crt = os.path.join(client_dir, 'cau.crt.pem')
    self._client_crl         = os.path.join(client_dir, 'cas.crl.pem')
    self._client_user_crl    = os.path.join(client_dir, 'cau.crl.pem')

425
    self._server_event = threading.Event()
Vincent Pelletier's avatar
Vincent Pelletier committed
426 427 428 429 430
    self._server_dir = server_dir = os.path.join(data_dir, 'server')
    os.mkdir(server_dir)
    self._server_db          = os.path.join(server_dir, 'caucase.sqlite')
    self._server_key         = os.path.join(server_dir, 'server.key.pem')
    self._server_backup_path = os.path.join(server_dir, 'backup')
431
    self._server_cors_store  = os.path.join(server_dir, 'cors.key')
432 433 434
    # Using a BytesIO for caucased output here, because stdout/stderr do not
    # necessarily have a known encoding, for example when output is a pipe
    # (to a file, ...). caucased must deal with this.
Vincent Pelletier's avatar
Vincent Pelletier committed
435
    self.caucase_test_output = BytesIO()
Vincent Pelletier's avatar
Vincent Pelletier committed
436 437
    os.mkdir(self._server_backup_path)

Vincent Pelletier's avatar
Vincent Pelletier committed
438 439 440 441
    self._server_netloc = netloc = os.getenv(
      'CAUCASE_NETLOC',
      'localhost:8000',
    )
Vincent Pelletier's avatar
Vincent Pelletier committed
442
    self._caucase_url = 'http://' + netloc
443
    parsed_url = urllib_parse.urlparse(self._caucase_url)
444 445 446 447 448 449 450 451

    try:
      ipaddress.ip_address(parsed_url.hostname)
    except ValueError:
      pass # parsed_url.hostname is a hostname as expected
    else: # pragma: no cover
      raise AssertionError('CAUCASE_NETLOC should not contains literal IP')

Vincent Pelletier's avatar
Vincent Pelletier committed
452 453 454 455 456
    self.assertFalse(
      canConnect((parsed_url.hostname, parsed_url.port)),
      'Something else is already listening on %r, define CAUCASE_NETLOC '
      'environment variable with a different ip/port' % (netloc, ),
    )
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
    # Starting caucased the first time is expensive: it needs to create at
    # least 4 asymetric key pairs (CAU, CAS, HTTP CA, HTTP cert). This can
    # take over 40 seconds on a Raspberry Pi 1 (which is the low-end platform
    # which should reliably pass these tests).
    # So backup the database after the first start, and restore it on further
    # starts. Save it as an in-memory uncompressed tarball (should be under a
    # megabyte).
    # This is intentionally independent from caucased own backup mechanism.
    if _clean_caucased_snapshot is None:
      self._startServer(timeout=60)
      self._stopServer()
      server_raw = BytesIO()
      with tarfile.TarFile(mode='w', fileobj=server_raw) as server_tarball:
        server_tarball.add(
          self._server_dir,
          arcname=os.path.basename(self._server_dir),
        )
      _clean_caucased_snapshot = server_raw.getvalue()
    else:
      with tarfile.TarFile(
        mode='r',
        fileobj=BytesIO(_clean_caucased_snapshot),
      ) as server_tarball:
        server_tarball.extractall(path=self._data_dir)
Vincent Pelletier's avatar
Vincent Pelletier committed
481 482
    self._startServer()

Vincent Pelletier's avatar
Vincent Pelletier committed
483
  @print_buffer_on_error
Vincent Pelletier's avatar
Vincent Pelletier committed
484 485 486 487 488 489 490 491
  def tearDown(self):
    """
    Stop any running caucased and delete all test data files.
    """
    if self._server.is_alive():
      self._stopServer()
    shutil.rmtree(self._data_dir)

492 493 494 495 496
  @staticmethod
  def _getCAKeyPair(extension_list=(), not_before=None, not_after=None):
    """
    Build a reasonably-realistic CA, return key & self-signed cert.
    """
497
    if not_before is None: # pragma: no cover
498
      not_before = datetime.datetime.utcnow()
499
    if not_after is None: # pragma: no cover
500
      not_after = not_before + datetime.timedelta(days=10)
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
    private_key = utils.generatePrivateKey(2048)
    subject = x509.Name([
      x509.NameAttribute(
        oid=x509.oid.NameOID.COMMON_NAME,
        value=u'John Doe CA',
      ),
    ])
    public_key = private_key.public_key()
    return private_key, x509.CertificateBuilder(
      subject_name=subject,
      issuer_name=subject,
      not_valid_before=not_before,
      not_valid_after=not_after,
      serial_number=x509.random_serial_number(),
      public_key=public_key,
      extensions=[
        Extension(
518
          x509.SubjectKeyIdentifier.from_public_key(public_key),
519 520 521
          critical=False, # "MUST mark this extension as non-critical"
        ),
        Extension(
522
          x509.AuthorityKeyIdentifier.from_issuer_public_key(public_key),
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
          critical=False, # "MUST mark this extension as non-critical"
        ),
        Extension(
          x509.BasicConstraints(
            ca=True,
            path_length=0,
          ),
          critical=True, # "MUST mark the extension as critical"
        ),
        Extension(
          x509.KeyUsage(
            digital_signature =False,
            content_commitment=False,
            key_encipherment  =False,
            data_encipherment =False,
            key_agreement     =False,
            key_cert_sign     =True,
            crl_sign          =True,
            encipher_only     =False,
            decipher_only     =False,
          ),
          critical=True, # "SHOULD mark this extension critical"
        ),
      ] + list(extension_list),
    ).sign(
      private_key=private_key,
      algorithm=hashes.SHA256(),
      backend=_cryptography_backend,
    )

  @staticmethod
  def _getKeyPair(
    ca_key,
    ca_crt,
    extension_list=(),
    not_before=None,
    not_after=None,
  ):
    """
    Build a reasonably-realistic signed cert, return key & self-signed cert.
    """
564
    if not_before is None: # pragma: no cover
565
      not_before = datetime.datetime.utcnow()
566
    if not_after is None: # pragma: no cover
567
      not_after = not_before + datetime.timedelta(days=10)
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
    crt_key = utils.generatePrivateKey(2048)
    return crt_key, x509.CertificateBuilder(
      subject_name=x509.Name([
        x509.NameAttribute(
          oid=x509.oid.NameOID.ORGANIZATIONAL_UNIT_NAME,
          value=u'Jane Doe',
        ),
      ]),
      issuer_name=ca_crt.subject,
      not_valid_before=not_before,
      not_valid_after=not_after,
      serial_number=x509.random_serial_number(),
      public_key=crt_key.public_key(),
      extensions=[
        Extension(
          x509.KeyUsage(
            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,
          ),
          critical=True,
        ),
      ] + list(extension_list),
    ).sign(
      private_key=ca_key,
      algorithm=hashes.SHA256(),
      backend=_cryptography_backend,
    )

603 604 605 606 607 608 609 610 611 612 613 614
  @staticmethod
  def _getCRL(
    ca_key,
    ca_crt,
    crl_number=1,
    revoked_serial_list=(),
    last_update=None,
    next_update=None,
  ):
    if last_update is None: # pragma: no cover
      last_update = datetime.datetime.utcnow()
    if next_update is None: # pragma: no cover
615
      next_update = last_update + datetime.timedelta(days=5)
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
    return x509.CertificateRevocationListBuilder(
      issuer_name=ca_crt.issuer,
      last_update=last_update,
      next_update=next_update,
      extensions=[
        Extension(
          x509.CRLNumber(crl_number),
          critical=False,
        ),
        Extension(
          ca_crt.extensions.get_extension_for_class(
            x509.AuthorityKeyIdentifier,
          ).value,
          critical=False,
        ),
      ],
      revoked_certificates=[
        x509.RevokedCertificateBuilder(
          serial_number=x['serial'],
          revocation_date=utils.timestamp2datetime(x['revocation_date']),
        ).build(_cryptography_backend) # pragma: no cover
        for x in revoked_serial_list
      ],
    ).sign(
      private_key=ca_key,
      algorithm=hashes.SHA256(),
      backend=_cryptography_backend,
    )

  def _getClientCRLList(self):
    return [
      x509.load_pem_x509_crl(x, _cryptography_backend)
      for x in utils.getCRLList(self._client_crl)
    ]
650

651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
  def _skipIfOpenSSLDoesNotSupportIPContraints(self):
    ca_key, ca_crt = self._getCAKeyPair(
      extension_list=[
        Extension(
          x509.NameConstraints(
            permitted_subtrees=[
              x509.IPAddress(ipaddress.ip_network(u'127.0.0.1')),
            ],
            excluded_subtrees=None,
          ),
          critical=True,
        ),
      ],
    )
    _, crt = self._getKeyPair(
      ca_key=ca_key,
      ca_crt=ca_crt,
    )
    try:
      # pylint: disable=protected-access
      utils._verifyCertificateChain(
        cert=crt,
        trusted_cert_list=[ca_crt],
674
        crl_list=None,
675 676
      )
      # pylint: enable=protected-access
Vincent Pelletier's avatar
Vincent Pelletier committed
677
    except CertificateVerificationError: # pragma: no cover
678 679
      raise unittest.SkipTest('OpenSSL versoin does not support IP constraints')

Vincent Pelletier's avatar
Vincent Pelletier committed
680 681 682 683 684 685 686 687
  def _restoreServer(
    self,
    backup_path,
    key_path,
    new_csr_path,
    new_key_path,
  ):
    """
688
    Start caucased-manage --restore-backup .
Vincent Pelletier's avatar
Vincent Pelletier committed
689 690
    Returns its exit status.
    """
691
    try:
692
      caucase.http.manage(
693
        argv=(
Vincent Pelletier's avatar
Vincent Pelletier committed
694 695 696 697 698 699 700
          '--db', self._server_db,
          '--restore-backup',
          backup_path,
          key_path,
          new_csr_path,
          new_key_path,
        ),
701
      )
702
    except SystemExit as e:
703
      return e.code # pragma: no cover
704
    except: # pylint: disable=bare-except
705 706 707
      return 1
    return 0

708
  def _startServer(self, argv=(), timeout=10):
Vincent Pelletier's avatar
Vincent Pelletier committed
709 710 711
    """
    Start caucased server
    """
712
    self._server_until = until = UntilEvent(self._server_event, None)
713
    self._server = server = threading.Thread(
714
      target=caucase.http.main,
Vincent Pelletier's avatar
Vincent Pelletier committed
715 716 717 718 719 720 721
      kwargs={
        'argv': (
          '--db', self._server_db,
          '--server-key', self._server_key,
          '--netloc', self._server_netloc,
          #'--threshold', '31',
          #'--key-len', '2048',
722
          '--cors-key-store', self._server_cors_store,
Vincent Pelletier's avatar
Vincent Pelletier committed
723
        ) + argv,
724
        'until': until,
Vincent Pelletier's avatar
Vincent Pelletier committed
725 726
        'log_file': self.caucase_test_output,
        'error_file': self.caucase_test_output,
Vincent Pelletier's avatar
Vincent Pelletier committed
727 728 729 730
      }
    )
    server.daemon = True
    server.start()
731
    parsed_url = urllib_parse.urlparse(self._caucase_url)
Vincent Pelletier's avatar
Vincent Pelletier committed
732
    if not retry(
733 734 735 736
      lambda: (
        self.assertTrue(server.is_alive(), 'caucased crashed on startup') or
        canConnect((parsed_url.hostname, parsed_url.port))
      ),
737
      try_count=timeout * 10,
738
    ): # pragma: no cover
Vincent Pelletier's avatar
Vincent Pelletier committed
739
      self._stopServer()
740
      raise AssertionError('Could not connect to %r after %i seconds' % (
Vincent Pelletier's avatar
Vincent Pelletier committed
741
        self._caucase_url,
742
        timeout,
Vincent Pelletier's avatar
Vincent Pelletier committed
743 744 745 746 747 748 749
      ))

  def _stopServer(self):
    """
    Stop a running caucased server
    """
    server = self._server
750
    self._server_until.action = ON_EVENT_RAISE
751
    self._server_event.set()
752
    server.join(60)
753
    if server.is_alive(): # pragma: no cover
754
      raise ValueError('%r does not wish to die' % (server, ))
Vincent Pelletier's avatar
Vincent Pelletier committed
755 756 757 758 759 760 761

  def _runClient(self, *argv):
    """
    Run client with given arguments.

    Returns stdout.
    """
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
    # Using a BytesIO for caucased output here, because stdout/stderr do not
    # necessarily have a known encoding, for example when output is a pipe
    # (to a file, ...). caucase must deal with this.
    stdout = BytesIO()
    try:
      cli.main(
        argv=(
          '--ca-url', self._caucase_url,
          '--ca-crt', self._client_ca_crt,
          '--user-ca-crt', self._client_user_ca_crt,
          '--crl', self._client_crl,
          '--user-crl', self._client_user_crl,
        ) + argv,
        stdout=stdout,
      )
    except SystemExit:
      pass
    return stdout.getvalue().decode('ascii')
Vincent Pelletier's avatar
Vincent Pelletier committed
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823

  @staticmethod
  def _setCertificateRemainingLifeTime(key, crt, delta):
    """
    Re-sign <crt> with <key>, shifting both its not_valid_before and
    not_valid_after dates so that its remaining validity period
    becomes <delta> and its validity span stays unchanged.
    """
    new_not_valid_after_date = datetime.datetime.utcnow() + delta
    return x509.CertificateBuilder(
      subject_name=crt.subject,
      issuer_name=crt.issuer,
      not_valid_before=new_not_valid_after_date - (
        crt.not_valid_after - crt.not_valid_before
      ),
      not_valid_after=new_not_valid_after_date,
      serial_number=crt.serial_number,
      public_key=crt.public_key(),
      extensions=crt.extensions,
    ).sign(
      private_key=key,
      algorithm=crt.signature_hash_algorithm,
      backend=_cryptography_backend,
    )

  def _setCACertificateRemainingLifeTime(self, mode, serial, delta):
    """
    Find the CA certificate with <serial> in caucase <mode> ("service"
    or "user") and pass it to _setCertificateRemainingLifeTime with <delta>.
    """
    int(serial) # Must already be an integer
    prefix = {
      'user': 'cau',
      'service': 'cas',
    }[mode]
    db = sqlite3.connect(self._server_db)
    db.row_factory = sqlite3.Row
    with db:
      c = db.cursor()
      c.execute(
        'SELECT rowid, key, crt FROM ' + prefix + 'ca',
      )
      while True:
        row = c.fetchone()
824
        if row is None: # pragma: no cover
Vincent Pelletier's avatar
Vincent Pelletier committed
825
          raise Exception('CA with serial %r not found' % (serial, ))
826
        crt = utils.load_ca_certificate(utils.toBytes(row['crt']))
Vincent Pelletier's avatar
Vincent Pelletier committed
827 828
        if crt.serial_number == serial:
          new_crt = self._setCertificateRemainingLifeTime(
829
            key=utils.load_privatekey(utils.toBytes(row['key'])),
Vincent Pelletier's avatar
Vincent Pelletier committed
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
            crt=crt,
            delta=delta,
          )
          new_crt_pem = utils.dump_certificate(new_crt)
          c.execute(
            'UPDATE ' + prefix + 'ca SET '
            'expiration_date=?, crt=? '
            'WHERE rowid=?',
            (
              utils.datetime2timestamp(new_crt.not_valid_after),
              new_crt_pem,
              row['rowid'],
            ),
          )
          return new_crt_pem

  def _getBaseName(self):
    """
    Returns a random file name, prefixed by data directory.
    """
    return os.path.join(
      self._data_dir,
      str(random.getrandbits(32)),
    )

  @staticmethod
  def _createPrivateKey(basename, key_len=2048):
    """
    Create a private key and store it to file.
    """
    name = basename + '.key.pem'
    assert not os.path.exists(name)
862
    with open(name, 'wb') as key_file:
Vincent Pelletier's avatar
Vincent Pelletier committed
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
      key_file.write(utils.dump_privatekey(
        utils.generatePrivateKey(key_len=key_len),
      ))
    return name

  @staticmethod
  def _getBasicCSRBuilder():
    """
    Initiate a minimal CSR builder.
    """
    return x509.CertificateSigningRequestBuilder(
      subject_name=x509.Name([
        x509.NameAttribute(
          oid=x509.oid.NameOID.COMMON_NAME,
          value=u'test',
        ),
      ]),
    )

  @staticmethod
  def _finalizeCSR(basename, key_path, csr_builder):
    """
    Sign, serialise and store given CSR Builder to file.
    """
    name = basename + '.csr.pem'
    assert not os.path.exists(name)
889
    with open(name, 'wb') as csr_file:
Vincent Pelletier's avatar
Vincent Pelletier committed
890 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 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 967 968 969 970 971 972 973 974 975 976
      csr_file.write(
        utils.dump_certificate_request(
          csr_builder.sign(
            private_key=utils.load_privatekey(utils.getKey(key_path)),
            algorithm=utils.DEFAULT_DIGEST_CLASS(),
            backend=_cryptography_backend,
          ),
        ),
      )
    return name

  def _createBasicCSR(self, basename, key_path):
    """
    Creates a basic CSR and returns its path.
    """
    return self._finalizeCSR(
      basename,
      key_path,
      self._getBasicCSRBuilder(),
    )

  def _createFirstUser(self, add_extensions=False):
    """
    Create first user, whose CSR is automatically signed.
    """
    basename = self._getBaseName()
    user_key_path = self._createPrivateKey(basename)
    csr_builder = self._getBasicCSRBuilder()
    if add_extensions:
      csr_builder = csr_builder.add_extension(
        x509.CertificatePolicies([
          x509.PolicyInformation(
            x509.oid.ObjectIdentifier(NOT_CAUCASE_OID),
            None,
          )
        ]),
        critical=False,
      )
    csr_path = self._finalizeCSR(
      basename,
      user_key_path,
      csr_builder,
    )
    out, = self._runClient(
      '--mode', 'user',
      '--send-csr', csr_path,
    ).splitlines()
    csr_id, csr_path_out = out.split()
    # Sanity check output
    self.assertEqual(csr_path, csr_path_out)
    int(csr_id)
    self.assertRaises(TypeError, utils.getCert, user_key_path)
    self._runClient(
      '--mode', 'user',
      '--get-crt', csr_id, user_key_path,
    )
    # Does not raise anymore, we have a certificate
    utils.getCert(user_key_path)
    return user_key_path

  def _createAndApproveCertificate(self, user_key_path, mode):
    """
    Create a CSR, submit it, approve it and retrieve the certificate.
    """
    basename = self._getBaseName()
    key_path = self._createPrivateKey(basename)
    csr_path = self._createBasicCSR(basename, key_path)
    out, = self._runClient(
      '--mode', mode,
      '--send-csr', csr_path,
    ).splitlines()
    csr_id, csr_path_out = out.split()
    # Sanity check output
    self.assertEqual(csr_path, csr_path_out)
    int(csr_id)
    self.assertRaises(TypeError, utils.getCert, key_path)
    out = self._runClient(
      '--mode', mode,
      '--get-crt', csr_id, key_path,
    ).splitlines()
    self.assertRaises(TypeError, utils.getCert, key_path)
    self.assertEqual([csr_id + ' CSR still pending'], out)
    csr2_path = csr_path + '.2'
    self._runClient(
      '--mode', mode,
      '--get-csr', csr_id, csr2_path,
    )
977 978
    with open(csr_path, 'rb') as csr_file, open(csr2_path, 'rb') as csr2_file:
      self.assertEqual(csr_file.read(), csr2_file.read())
Vincent Pelletier's avatar
Vincent Pelletier committed
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 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 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
    # Sign using user cert
    # Note: assuming user does not know the csr_id and keeps their own copy of
    # issued certificates.
    out = self._runClient(
      '--mode', mode,
      '--user-key', user_key_path,
      '--list-csr',
    ).splitlines()
    self.assertEqual([csr_id], [x.split(None, 1)[0] for x in out[2:-1]])
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--mode', mode,
      '--user-key', user_key_path,
      '--sign-csr', str(int(csr_id) + 1),
    )
    out = self._runClient(
      '--mode', mode,
      '--user-key', user_key_path,
      '--sign-csr', csr_id,
    )
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--mode', mode,
      '--user-key', user_key_path,
      '--sign-csr', csr_id,
    )
    # Now requester can get their certificate
    out, = self._runClient(
      '--mode', mode,
      '--get-crt', csr_id, key_path,
    ).splitlines()
    # Does not raise anymore, we have a certificate
    utils.getCert(user_key_path)
    return key_path

  def testBasicUsage(self):
    """
    Everybody plays by the rules (which includes trying to access when
    revoked).
    """
    self.assertFalse(os.path.exists(self._client_ca_crt))
    self.assertFalse(os.path.exists(self._client_crl))
    self.assertFalse(os.path.exists(self._client_user_ca_crt))
    self.assertFalse(os.path.exists(self._client_user_crl))
    # Running client creates CAS files (service CA & service CRL)
    self._runClient()
    self.assertTrue(os.path.exists(self._client_ca_crt))
    self.assertTrue(os.path.exists(self._client_crl))
    self.assertFalse(os.path.exists(self._client_user_ca_crt))
    self.assertFalse(os.path.exists(self._client_user_crl))
    # Running in "user" mode also created the CAU CA, but not the CAU CRL
    self._runClient('--mode', 'user')
    self.assertTrue(os.path.exists(self._client_ca_crt))
    self.assertTrue(os.path.exists(self._client_crl))
    self.assertTrue(os.path.exists(self._client_user_ca_crt))
    self.assertFalse(os.path.exists(self._client_user_crl))

    cas_crt_list = [
      utils.load_ca_certificate(x)
      for x in utils.getCertList(self._client_ca_crt)
    ]
    cau_crt_list = [
      utils.load_ca_certificate(x)
      for x in utils.getCertList(self._client_user_ca_crt)
    ]
    # No CA renewal happened yet
    self.assertEqual(len(cas_crt_list), 1)
    self.assertEqual(len(cau_crt_list), 1)

    # Get a user key pair
    user_key_path = self._createFirstUser()
    # It must have been auto-signed
    self.assertTrue(utils.isCertificateAutoSigned(utils.load_certificate(
      # utils.getCert(user_key_path) does not raise anymore
      utils.getCert(user_key_path),
      cau_crt_list,
      None,
    )))

    # Get a not-auto-approved service crt (the first auto-approved one was for
    # the http server itself)
    service_key = self._createAndApproveCertificate(
      user_key_path,
      'service',
    )
    self.assertFalse(utils.isCertificateAutoSigned(utils.load_certificate(
      utils.getCert(service_key),
      cas_crt_list,
      None,
    )))

    # Get a not-auto-approved user crt
    user2_key_path = self._createAndApproveCertificate(
      user_key_path,
      'user',
    )
    self.assertFalse(utils.isCertificateAutoSigned(utils.load_certificate(
      utils.getCert(user2_key_path),
      cau_crt_list,
      None,
    )))
    # It can itself sign certificates...
    service2_key_path = self._createAndApproveCertificate(
      user2_key_path,
      'service',
    )
    user3_key_path = self._createAndApproveCertificate(
      user2_key_path,
      'user',
    )
    self._runClient(
      '--user-key', user2_key_path,
      '--list-csr',
    )
    self._runClient(
      '--mode', 'user',
      '--user-key', user2_key_path,
      '--list-csr',
    )
    # ...until it gets revoked
    self._runClient(
      '--user-key', user_key_path,
      '--mode', 'user',
      '--revoke-other-crt', user2_key_path,
      '--update-user',
    )
    self.assertRaises(
      CaucaseError,
      self._createAndApproveCertificate,
      user2_key_path,
      'service',
    )
    self.assertRaises(
      CaucaseError,
      self._createAndApproveCertificate,
      user2_key_path,
      'user',
    )
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--user-key', user2_key_path,
      '--list-csr',
    )
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--mode', 'user',
      '--user-key', user2_key_path,
      '--list-csr',
    )
    # But the user it approved still works...
    self._runClient(
      '--user-key', user3_key_path,
      '--list-csr',
    )
    # ...until it revokes itself
    self._runClient(
      '--mode', 'user',
      '--user-key', user3_key_path,
      '--revoke-serial', str(
        utils.load_certificate(
          utils.getCert(user3_key_path),
          cau_crt_list,
          None,
        ).serial_number,
      )
    )
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--user-key', user3_key_path,
      '--list-csr',
    )
    # And the service it approved works too
    service2_crt_before, service2_key_before, _ = utils.getKeyPair(
      service2_key_path,
    )
    self._runClient(
      # 100 days is longer than certificate life, so it will be immediately
      # renewed.
      '--threshold', '100',
      '--renew-crt', service2_key_path, '',
    )
    service2_crt_after, service2_key_after, _ = utils.getKeyPair(
      service2_key_path,
    )
    # Certificate and key were renewed...
    self.assertNotEqual(service2_crt_before, service2_crt_after)
    self.assertNotEqual(service2_key_before, service2_key_after)
    # ...and not just swapped
    self.assertNotEqual(service2_crt_before, service2_key_after)
    self.assertNotEqual(service2_key_before, service2_crt_after)
    # It can revoke itself...
    self._runClient(
      '--revoke-crt', service2_key_path, '',
    )
    # ...and then it cannot renew itself any more...
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--threshold', '100',
      '--renew-crt', service2_key_path, '',
    )
    service2_crt_after2, service2_key_after2, _ = utils.getKeyPair(
      service2_key_path,
    )
    # and crt & key did not change
    self.assertEqual(service2_crt_after, service2_crt_after2)
    self.assertEqual(service2_key_after, service2_key_after2)
    # revoking again one's own certificate fails
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--revoke-crt', service2_key_path, '',
    )
    # as does revoking with an authenticated user
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--user-key', user_key_path,
      '--revoke-other-crt', service2_key_path,
    )
    # and revoking by serial
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--user-key', user_key_path,
      '--revoke-serial', str(
        utils.load_certificate(
          utils.getCert(service2_key_path),
          cas_crt_list,
          None,
        ).serial_number,
      ),
    )

    # Rejecting a CSR
    basename = self._getBaseName()
    key_path = self._createPrivateKey(basename)
    csr_path = self._createBasicCSR(basename, key_path)
    out, = self._runClient(
      '--send-csr', csr_path,
    ).splitlines()
    csr_id, csr_path_out = out.split()
    # Sanity check output
    self.assertEqual(csr_path, csr_path_out)
    int(csr_id)
    self.assertRaises(TypeError, utils.getCert, key_path)
    out = self._runClient(
      '--get-crt', csr_id, key_path,
    ).splitlines()
    self.assertRaises(TypeError, utils.getCert, key_path)
    self.assertEqual([csr_id + ' CSR still pending'], out)
    out = self._runClient(
      '--user-key', user_key_path,
      '--reject-csr', csr_id,
    ).splitlines()
    # Re-rejecting fails
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--user-key', user_key_path,
      '--reject-csr', csr_id,
    )
    # like rejecting a non-existing crt
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--user-key', user_key_path,
      '--reject-csr', str(int(csr_id) + 1),
    )
    out = self._runClient(
      '--get-crt', csr_id, key_path,
    ).splitlines()
    self.assertRaises(TypeError, utils.getCert, key_path)
    self.assertEqual([
Vincent Pelletier's avatar
Vincent Pelletier committed
1258
      csr_id + ' not found - maybe CSR was rejected ?'
Vincent Pelletier's avatar
Vincent Pelletier committed
1259 1260
    ], out)

1261 1262 1263 1264 1265 1266 1267 1268 1269
    # The server is able to regenerate the same CRL after a restart
    reference_crl_list = self._getClientCRLList()
    assert reference_crl_list # Sanity check
    os.unlink(self._client_crl)
    self._stopServer()
    self._startServer()
    self._runClient()
    self.assertEqual(self._getClientCRLList(), reference_crl_list)

1270 1271
    # Renewing CRL
    self._stopServer()
1272
    reference_crl, = self._getClientCRLList()
1273 1274 1275 1276 1277
    now = datetime.datetime.utcnow()
    # x509 certificates have second-level accuracy
    now = now.replace(microsecond=0)
    # Sanity check: pre-existing CRL creation should be strictly in the past
    self.assertLess(reference_crl.last_update, now)
1278
    # Bump last_update in the past by a bit over half the CRL lifetime.
1279 1280 1281
    SQLite3Storage(
      self._server_db,
      table_prefix='cas',
1282
    ).storeCRLLastUpdate(
1283
      last_update=utils.datetime2timestamp(now - datetime.timedelta(days=16)),
1284
    )
1285 1286
    self._startServer()
    self._runClient()
1287
    new_crl, = self._getClientCRLList()
1288 1289 1290
    # May be equal due to lack of timestamp accuracy.
    self.assertLessEqual(now, new_crl.last_update)

1291 1292 1293 1294 1295 1296 1297 1298
  def testBadCSR(self):
    """
    Submitting an invalid CSR.

    Requires bypassing cli, as it does its own checks.
    """
    client = CaucaseClient(self._caucase_url + '/cas')
    try:
1299
      client.createCertificateSigningRequest('Not actually a CSR')
1300
    except CaucaseError as e:
1301
      self.assertEqual(e.args[0], 400, e)
1302
    else: # pragma: no cover
1303 1304
      raise AssertionError('Did not raise CaucaseError(400, ...)')

1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
  def testGetSingleCRL(self):
    """
    Retrieve an individual CRL.

    Requires bypassing cli, as it only updates all CRLs.
    """
    self._runClient()
    ca_crt_pem, = utils.getCertList(self._client_ca_crt)
    ca_crt = utils.load_ca_certificate(ca_crt_pem)
    ca_key_identifier = utils.getAuthorityKeyIdentifier(ca_crt)
    user_key_path = self._createFirstUser()
    service_key = self._createAndApproveCertificate(
      user_key_path,
      'service',
    )
    distribution_point, = utils.load_certificate(
      utils.getCert(service_key),
      [
        utils.load_ca_certificate(x)
        for x in utils.getCertList(self._client_ca_crt)
      ],
      None,
    ).extensions.get_extension_for_class(
      x509.CRLDistributionPoints,
    ).value
    crl_uri, = distribution_point.full_name
1331
    self.assertRegex(
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
      crl_uri.value,
      u'/cas/crl/%i$' % (ca_key_identifier, ),
    )
    reference_client_crl_pem, = utils.getCRLList(self._client_crl)
    self.assertEqual(
      CaucaseClient(
        self._caucase_url + '/cas',
      ).getCertificateRevocationList(ca_key_identifier),
      reference_client_crl_pem,
    )

Vincent Pelletier's avatar
Vincent Pelletier committed
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
  def testUpdateUser(self):
    """
    Verify that CAU certificate and revocation list are created when the
    (rarely needed) --update-user option is given.
    """
    self.assertFalse(os.path.exists(self._client_ca_crt))
    self.assertFalse(os.path.exists(self._client_crl))
    self.assertFalse(os.path.exists(self._client_user_ca_crt))
    self.assertFalse(os.path.exists(self._client_user_crl))
    self._runClient('--update-user')
    self.assertTrue(os.path.exists(self._client_ca_crt))
    self.assertTrue(os.path.exists(self._client_crl))
    self.assertTrue(os.path.exists(self._client_user_ca_crt))
    self.assertTrue(os.path.exists(self._client_user_crl))

  def testMaxCSR(self):
    """
    Verify that the number of pending CSR is properly constrained.
    """
    csr_list = []
    def assertCanSend(count):
      """
      Check that caucased accepts <count> CSR, and rejects the next one.
      Appends the data of created CSRs (csr_id and csr_path) to csr_list.
      """
1368
      for _ in range(count):
Vincent Pelletier's avatar
Vincent Pelletier committed
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
        basename = self._getBaseName()
        csr_path = self._createBasicCSR(
          basename,
          self._createPrivateKey(basename),
        )
        out, = self._runClient('--send-csr', csr_path).splitlines()
        csr_id, _ = out.split()
        csr_list.append((csr_id, csr_path))
      basename = self._getBaseName()
      bad_csr_path = self._createBasicCSR(
        basename,
        self._createPrivateKey(basename),
      )
      self.assertRaises(
        CaucaseError,
        self._runClient,
        '--send-csr',
        bad_csr_path,
      )

    user_key_path = self._createFirstUser()
    self._stopServer()
1391
    self._startServer((
Vincent Pelletier's avatar
Vincent Pelletier committed
1392
      '--service-max-csr', '5',
1393
    ))
Vincent Pelletier's avatar
Vincent Pelletier committed
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
    assertCanSend(5)
    # But resubmitting one of the accepted ones is still fine
    _, csr_path = csr_list[0]
    self._runClient('--send-csr', csr_path)

    # Accepted certificates do not count towards the total, even if not
    # retrieved by owner
    csr_id, csr_path = csr_list.pop()
    self._runClient(
      '--user-key', user_key_path,
      '--sign-csr', csr_id,
    )
    assertCanSend(1)
    # Rejected certificates do not count towards the total.

    csr_id, _ = csr_list.pop()
    self._runClient(
      '--user-key', user_key_path,
      '--reject-csr', csr_id,
    )
    assertCanSend(1)

  def testLockAutoSignAmount(self):
    """
    Verify that auto-approve limit freezing works.
    """
    self._stopServer()
1421
    self._startServer((
Vincent Pelletier's avatar
Vincent Pelletier committed
1422 1423
      '--user-auto-approve-count', '2',
      '--lock-auto-approve-count',
1424
    ))
Vincent Pelletier's avatar
Vincent Pelletier committed
1425
    self._stopServer()
1426
    self._startServer((
Vincent Pelletier's avatar
Vincent Pelletier committed
1427
      '--user-auto-approve-count', '3',
1428
    ))
Vincent Pelletier's avatar
Vincent Pelletier committed
1429 1430 1431 1432
    self._createFirstUser()
    self._createFirstUser()
    self.assertRaises(TypeError, self._createFirstUser)
    self._stopServer()
1433
    self._startServer((
Vincent Pelletier's avatar
Vincent Pelletier committed
1434 1435
      '--user-auto-approve-count', '3',
      '--lock-auto-approve-count',
1436
    ))
Vincent Pelletier's avatar
Vincent Pelletier committed
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
    self.assertRaises(TypeError, self._createFirstUser)

  def testCSRFiltering(self):
    """
    Verify that requester cannot get any extension or extension value they
    ask for. Caucase has to protect itself to be trustworthy, but also to let
    some liberty to requester.
    """
    def checkCRT(key_path):
      """
      Verify key_path to contain exactly one certificate, itself containing
      all expected extensions.
      """
      crt = utils.load_certificate(
        utils.getCert(key_path),
        cas_crt_list,
        None,
      )
      # CA-only extension, must not be present in certificate
      self.assertRaises(
        x509.ExtensionNotFound,
        crt.extensions.get_extension_for_class,
        x509.NameConstraints,
      )
      for expected_value in [
        expected_key_usage,
        expected_extended_usage,
        expected_alt_name,
        expected_policies,
        expected_basic_constraints,
      ]:
        extension = crt.extensions.get_extension_for_class(
          expected_value.__class__,
        )
        self.assertEqual(
          extension.value,
          expected_value,
        )
        self.assertTrue(extension.critical)
    requested_key_usage = x509.KeyUsage(
      digital_signature =True,
      content_commitment=True,
      key_encipherment  =True,
      data_encipherment =True,
      key_agreement     =True,
      key_cert_sign     =True,
      crl_sign          =True,
      encipher_only     =True,
      decipher_only     =False,
    )
    expected_key_usage = x509.KeyUsage(
      digital_signature =True,
      content_commitment=True,
      key_encipherment  =True,
      data_encipherment =True,
      key_agreement     =True,
      key_cert_sign     =False,
      crl_sign          =False,
      encipher_only     =True,
      decipher_only     =False,
    )
    requested_extended_usage = x509.ExtendedKeyUsage([
      x509.oid.ExtendedKeyUsageOID.OCSP_SIGNING,
      x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH,
    ])
    expected_extended_usage = x509.ExtendedKeyUsage([
      x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH,
    ])
    requested_alt_name = expected_alt_name = x509.SubjectAlternativeName([
1506 1507 1508
      x509.RFC822Name(u'nobody@example.com'),
      x509.DNSName(u'example.com'),
      x509.UniformResourceIdentifier(u'https://example.com/a/b/c'),
Vincent Pelletier's avatar
Vincent Pelletier committed
1509 1510 1511 1512 1513
      x509.IPAddress(ipaddress.IPv4Address(u'127.0.0.1')),
      x509.IPAddress(ipaddress.IPv6Address(u'::1')),
      x509.IPAddress(ipaddress.IPv4Network(u'127.0.0.0/8')),
      x509.IPAddress(ipaddress.IPv6Network(u'::/64')),
    ])
1514
    policy_list = [
Vincent Pelletier's avatar
Vincent Pelletier committed
1515 1516 1517 1518 1519 1520 1521 1522
      x509.PolicyInformation(
        x509.oid.ObjectIdentifier(utils.CAUCASE_OID_RESERVED),
        None,
      ),
      x509.PolicyInformation(
        x509.oid.ObjectIdentifier(NOT_CAUCASE_OID),
        None,
      ),
1523 1524 1525 1526 1527 1528 1529 1530 1531
    ]
    if _HAS_LONG_OID_SUPPORT: # pragma: no cover
      policy_list.append(
        x509.PolicyInformation(
          x509.oid.ObjectIdentifier(utils.CAUCASE_LEGACY_OID_RESERVED),
          None,
        ),
      )
    requested_policies = x509.CertificatePolicies(policy_list)
Vincent Pelletier's avatar
Vincent Pelletier committed
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
    expected_policies = x509.CertificatePolicies([
      x509.PolicyInformation(
        x509.oid.ObjectIdentifier(NOT_CAUCASE_OID),
        None,
      ),
    ])
    requested_basic_constraints = x509.BasicConstraints(
      ca=True,
      path_length=42,
    )
    expected_basic_constraints = x509.BasicConstraints(
      ca=False,
      path_length=None,
    )

    # Check stored CSR filtering
    user_key_path = self._createFirstUser(add_extensions=True)
    basename = self._getBaseName()
    key_path = self._createPrivateKey(basename)
    requested_csr_path = self._finalizeCSR(
      basename,
      key_path,
      self._getBasicCSRBuilder(
      ).add_extension(requested_key_usage, critical=True,
      ).add_extension(requested_extended_usage, critical=True,
      ).add_extension(requested_alt_name, critical=True,
      ).add_extension(requested_policies, critical=True,
      ).add_extension(requested_basic_constraints, critical=True,
      ).add_extension(
1561
        x509.NameConstraints([x509.DNSName(u'com')], None),
Vincent Pelletier's avatar
Vincent Pelletier committed
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
        critical=True,
      ),
    )
    out, = self._runClient(
      '--send-csr', requested_csr_path,
    ).splitlines()
    csr_id, _ = out.split()
    int(csr_id)
    self._runClient(
      '--user-key', user_key_path,
      '--sign-csr', csr_id,
    )
    self._runClient(
      '--get-crt', csr_id, key_path,
    )
    cas_crt_list = [
      utils.load_ca_certificate(x)
      for x in utils.getCertList(self._client_ca_crt)
    ]
    cau_crt_list = [
      utils.load_ca_certificate(x)
      for x in utils.getCertList(self._client_user_ca_crt)
    ]
    checkCRT(key_path)

    # Check renewed CRT filtering does not alter clean signed certificate
    # content (especially, caucase auto-signed flag must not appear).
1589 1590
    with open(key_path, 'rb') as key_file:
      before_key = key_file.read()
Vincent Pelletier's avatar
Vincent Pelletier committed
1591 1592 1593 1594
    self._runClient(
      '--threshold', '100',
      '--renew-crt', key_path, '',
    )
1595 1596
    with open(key_path, 'rb') as key_file:
      after_key = key_file.read()
Vincent Pelletier's avatar
Vincent Pelletier committed
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
    assert before_key != after_key
    checkCRT(key_path)

    # Check content of auto-issued user certificate
    user_crt = utils.load_certificate(
      utils.getCert(user_key_path),
      cau_crt_list,
      None,
    )
    user_certificate_policies = user_crt.extensions.get_extension_for_class(
      x509.CertificatePolicies,
    )
    self.assertEqual(
      user_certificate_policies.value,
      x509.CertificatePolicies([
        x509.PolicyInformation(
          x509.oid.ObjectIdentifier(NOT_CAUCASE_OID),
          None,
        ),
        utils.CAUCASE_POLICY_INFORMATION_AUTO_SIGNED,
      ]),
    )
    self.assertFalse(user_certificate_policies.critical)

    # Check template CSR: must be taken into account, but it also gets
    # filtered.
    basename2 = self._getBaseName()
    key_path2 = self._createPrivateKey(basename2)
    out, = self._runClient(
      '--send-csr', self._finalizeCSR(
        basename2,
        key_path2,
        self._getBasicCSRBuilder(),
      ),
    ).splitlines()
    csr_id, _ = out.split()
    int(csr_id)
    self._runClient(
      '--user-key', user_key_path,
      '--sign-csr-with', csr_id, requested_csr_path,
    )
    self._runClient(
      '--get-crt', csr_id, key_path2,
    )
    checkCRT(key_path2)

  def testCACertRenewal(self):
    """
    Exercise CA certificate rollout procedure.
1646
    Also, check CaucaseClient.updateCAFile and CaucaseClient.updateCRLFile.
Vincent Pelletier's avatar
Vincent Pelletier committed
1647
    """
1648 1649 1650 1651 1652
    def _checkUserAccess(user):
      self._runClient(
        '--user-key', user,
        '--list-csr', # Whatever restricted operation
      )
Vincent Pelletier's avatar
Vincent Pelletier committed
1653
    user_key_path = self._createFirstUser()
1654
    cau_ca_list = [
Vincent Pelletier's avatar
Vincent Pelletier committed
1655 1656 1657
      utils.load_ca_certificate(x)
      for x in utils.getCertList(self._client_user_ca_crt)
    ]
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
    cau_crt, = cau_ca_list
    caucase_url = self._caucase_url + '/cau'
    updateCAFile = lambda: CaucaseClient.updateCAFile(
      url=caucase_url,
      ca_crt_path=self._client_user_ca_crt,
    )
    updateCRLFile = lambda: CaucaseClient.updateCRLFile(
      url=caucase_url,
      crl_path=self._client_user_crl,
      ca_list=cau_ca_list,
    )
    self._runClient('--update-user')
    # CA & CRL were freshly updated, they should not need any update
    self.assertFalse(updateCAFile())
    self.assertFalse(updateCRLFile())
    os.unlink(self._client_user_ca_crt)
    os.unlink(self._client_user_crl)
    # CA & CRL were emptied, they need update
    self.assertTrue(updateCAFile())
    self.assertTrue(updateCRLFile())
    # And there is no need for further updates
    self.assertFalse(updateCAFile())
    self.assertFalse(updateCRLFile())
Vincent Pelletier's avatar
Vincent Pelletier committed
1681
    self._stopServer()
1682
    # CA expires in 100 days: longer than one certificate life (93 days),
Vincent Pelletier's avatar
Vincent Pelletier committed
1683 1684
    # but shorter than two. A new CA must be generated and distributed,
    # but not used for new signatures yet.
1685 1686 1687
    # As we will use this crt as trust anchor, we must make the client believe
    # it knew it all along.
    old_cau_pem = self._setCACertificateRemainingLifeTime(
Vincent Pelletier's avatar
Vincent Pelletier committed
1688 1689
      'user',
      cau_crt.serial_number,
1690
      datetime.timedelta(days=100),
Vincent Pelletier's avatar
Vincent Pelletier committed
1691
    )
1692
    utils.saveCertList(self._client_user_ca_crt, [old_cau_pem])
1693
    self._startServer(timeout=20)
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
    # There is a new CA (and its CRL), update is needed.
    self.assertTrue(updateCAFile())
    # Load the new CA so CRL validation succeeds
    cau_ca_list = [
      utils.load_ca_certificate(x)
      for x in utils.getCertList(self._client_user_ca_crt)
    ]
    self.assertTrue(updateCRLFile())
    # And there is no need for further updates
    self.assertFalse(updateCAFile())
    self.assertFalse(updateCRLFile())
    user1_key = self._createAndApproveCertificate(
      user_key_path,
      'user',
    )
    user2_key = self._createAndApproveCertificate(
Vincent Pelletier's avatar
Vincent Pelletier committed
1710 1711 1712 1713 1714
      user_key_path,
      'user',
    )
    # Must not raise: we are signed with the "old" ca.
    utils.load_certificate(
1715
      utils.getCert(user2_key),
Vincent Pelletier's avatar
Vincent Pelletier committed
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
      [cau_crt],
      None,
    )
    # We must now know the new CA
    cau_crt_list = [
      utils.load_ca_certificate(x)
      for x in utils.getCertList(self._client_user_ca_crt)
    ]
    new_cau_crt, = [
      x for x in cau_crt_list
      if x.serial_number != cau_crt.serial_number
    ]
    self._stopServer()
    # New CA now exists for 100 days: longer than one certificate life.
    # It may (must) be used for new signatures.
1731 1732 1733 1734
    new_cau_pem = self._setCACertificateRemainingLifeTime(
      'user',
      new_cau_crt.serial_number,
      new_cau_crt.not_valid_after - new_cau_crt.not_valid_before -
1735
      datetime.timedelta(days=100),
1736
    )
1737 1738
    utils.saveCertList(
      self._client_user_ca_crt,
1739
      [old_cau_pem, new_cau_pem],
Vincent Pelletier's avatar
Vincent Pelletier committed
1740 1741
    )
    self._startServer()
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
    # New certificate is signed by the new CA.
    # Also, checks that user_key_path, which was signed by the old CA, is still
    # accepted.
    user3_key = self._createAndApproveCertificate(
      user_key_path,
      'user',
    )
    self.assertRaises(
      exceptions.CertificateVerificationError,
      utils.load_certificate,
      utils.getCert(user3_key),
      [cau_crt],
      None,
    )
    utils.load_certificate(
      utils.getCert(user3_key),
      cau_crt_list,
      None,
1760
    )
1761
    # Renewing a certificate gets one signed by the new CA
Vincent Pelletier's avatar
Vincent Pelletier committed
1762 1763 1764 1765 1766
    self._runClient(
      '--mode', 'user',
      # 100 days is longer than certificate life, so it will be immediately
      # renewed.
      '--threshold', '100',
1767
      '--renew-crt', user2_key, '',
Vincent Pelletier's avatar
Vincent Pelletier committed
1768 1769 1770 1771
    )
    self.assertRaises(
      exceptions.CertificateVerificationError,
      utils.load_certificate,
1772
      utils.getCert(user2_key),
Vincent Pelletier's avatar
Vincent Pelletier committed
1773 1774 1775 1776
      [cau_crt],
      None,
    )
    utils.load_certificate(
1777
      utils.getCert(user2_key),
Vincent Pelletier's avatar
Vincent Pelletier committed
1778 1779 1780
      cau_crt_list,
      None,
    )
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
    # This user certificate is accepted too.
    _checkUserAccess(user2_key)
    # Revoking a certificate signed by the old CA works.
    _checkUserAccess(user1_key)
    self._runClient(
      '--mode', 'user',
      '--revoke-crt', user1_key, '',
    )
    self.assertRaises(CaucaseError, _checkUserAccess, user1_key)
    # Revoking a certificate signed by the new CA works.
    _checkUserAccess(user2_key)
    self._runClient(
      '--mode', 'user',
      '--revoke-crt', user2_key, '',
      '--update-user',
    )
    # The CRLs maintained by the client have been refreshed to include the
    # latest revocation, and all CRLs contain it.
    expected_serial_set = {
      utils.load_certificate(
        utils.getCert(x),
        cau_ca_list,
        None,
      ).serial_number
      for x in (user1_key, user2_key)
    }
    # Test sanity check
    assert len(expected_serial_set) == 2, expected_serial_set
    crl_pem_a, crl_pem_b = utils.getCRLList(self._client_user_crl)
    self.assertItemsEqual(
      expected_serial_set,
      [x.serial_number for x in utils.load_crl(crl_pem_a, cau_ca_list)],
    )
    self.assertItemsEqual(
      expected_serial_set,
      [x.serial_number for x in utils.load_crl(crl_pem_b, cau_ca_list)],
    )
    self.assertRaises(CaucaseError, _checkUserAccess, user2_key)
1819 1820 1821 1822 1823 1824 1825 1826 1827
    # A client without established trust anchor gets all still-valid CA
    # certificates, not just the active one, so they can check still-valid
    # certificates issued on the CA being retired.
    os.unlink(self._client_user_ca_crt)
    self._runClient('--mode', 'user')
    self.assertItemsEqual(
      [old_cau_pem, new_cau_pem],
      utils.getCertList(self._client_user_ca_crt),
    )
1828 1829 1830 1831 1832
    # The old CA is now fully expired
    self._stopServer()
    old_cau_pem = self._setCACertificateRemainingLifeTime(
      'user',
      cau_crt.serial_number,
1833
      datetime.timedelta(days=-1),
1834 1835 1836 1837 1838 1839
    )
    utils.saveCertList(
      self._client_user_ca_crt,
      [old_cau_pem, new_cau_pem],
    )
    self._startServer()
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
    # The old CA certificate is properly expired
    self.assertRaises(
      exceptions.CertificateVerificationError,
      utils.load_ca_certificate,
      old_cau_pem,
    )
    # Loading the CRL signed by the old CA certificate fails
    new_cau = utils.load_ca_certificate(new_cau_pem)
    try:
      for crl_pem in (crl_pem_a, crl_pem_b):
        utils.load_crl(crl_pem, [new_cau])
    except cryptography.exceptions.InvalidSignature:
      pass
    else:
      raise AssertionError(
        'cryptography.exceptions.InvalidSignature was not raised',
      )
    # CA renewal works
    updateCAFile()
1859 1860 1861 1862 1863 1864 1865 1866
    # Non-renewed user certificate is rejected
    self.assertRaises(CaucaseError, _checkUserAccess, user_key_path)
    # Revoked and non-renewed user certificate is rejected
    self.assertRaises(CaucaseError, _checkUserAccess, user1_key)
    # Revoked and renewed user certificate is rejected
    self.assertRaises(CaucaseError, _checkUserAccess, user2_key)
    # Renewed and non-revoked user certificate is accepted
    _checkUserAccess(user3_key)
1867 1868
    # A client without established trust anchor only gets valid CA certs.
    os.unlink(self._client_user_ca_crt)
1869
    self._runClient('--mode', 'user', '--update-user')
1870 1871 1872 1873
    self.assertItemsEqual(
      [new_cau_pem],
      utils.getCertList(self._client_user_ca_crt),
    )
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
    # A client with only expired trust anchor does not get a new CA
    utils.saveCertList(
      self._client_user_ca_crt,
      [old_cau_pem],
    )
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--mode', 'user', '--update-user',
    )
    self.assertItemsEqual(
      [old_cau_pem],
      utils.getCertList(self._client_user_ca_crt),
    )
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908

  def testCaucasedCRLRenewal(self):
    """
    Renew a CRL which has reached its renewal time.
    """
    self._stopServer()
    cau = CertificateAuthority(
      storage=SQLite3Storage(
        db_path=self._server_db,
        table_prefix='cas',
      ),
    )
    # Fill the cache
    reference_crl_pem_dict = cau.getCertificateRevocationListDict()
    # Artificially expire all cached CRLs
    # pylint: disable=protected-access
    crl_pem_dict = cau._current_crl_dict
    # pylint: enable=protected-access
    for (
      authority_key_identifier,
      (crl_pem, _),
1909
    ) in list(crl_pem_dict.items()):
1910 1911
      crl_pem_dict[authority_key_identifier] = (
        crl_pem,
1912
        datetime.datetime.utcnow() - datetime.timedelta(seconds=1),
1913 1914 1915 1916 1917 1918 1919 1920
      )
    cau_ca_list = cau.getCACertificateList()
    new_crl_pem_dict = cau.getCertificateRevocationListDict()
    self.assertTrue(reference_crl_pem_dict)
    self.assertItemsEqual(reference_crl_pem_dict, new_crl_pem_dict)
    for (
      authority_key_identifier,
      reference_crl_pem,
1921
    ) in reference_crl_pem_dict.items():
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
      self.assertEqual(
        utils.load_crl(
          new_crl_pem_dict[authority_key_identifier],
          cau_ca_list,
        ).extensions.get_extension_for_class(
          x509.CRLNumber,
        ).value.crl_number,
        utils.load_crl(
          reference_crl_pem,
          cau_ca_list,
        ).extensions.get_extension_for_class(
          x509.CRLNumber,
        ).value.crl_number + 1,
      )
Vincent Pelletier's avatar
Vincent Pelletier committed
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945

  def testCaucasedCertRenewal(self):
    """
    Exercise caucased internal certificate renewal procedure.
    """
    user_key_path = self._createFirstUser()
    self._stopServer()
    # If server certificate is deleted, it gets re-created, even it CAS
    # reached its certificate auto-approval limit.
    os.unlink(self._server_key)
1946
    self._startServer(timeout=20)
1947
    if not retry(lambda: os.path.exists(self._server_key)): # pragma: no cover
Vincent Pelletier's avatar
Vincent Pelletier committed
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
      raise AssertionError('%r was not recreated within 1 second' % (
        self._server_key,
      ))
    # But user still trusts the server
    self._runClient(
      '--mode', 'user',
      # 100 days is longer than certificate life, so it will be immediately
      # renewed.
      '--threshold', '100',
      '--renew-crt', user_key_path, '',
    )
    # Server certificate will expire in 20 days, the key must be renewed
1960 1961
    # (but we have to peek at HTTP CAS private key, cover your eyes)
    (http_cas_key, ), = sqlite3.connect(
Vincent Pelletier's avatar
Vincent Pelletier committed
1962 1963
      self._server_db,
    ).cursor().execute(
1964
      'SELECT key FROM http_casca',
Vincent Pelletier's avatar
Vincent Pelletier committed
1965 1966 1967
    ).fetchall()

    self._stopServer()
1968
    crt_pem, key_pem, ca_crt_pem = utils.getCertKeyAndCACert(
Vincent Pelletier's avatar
Vincent Pelletier committed
1969
      self._server_key,
1970
      crl_list=None,
Vincent Pelletier's avatar
Vincent Pelletier committed
1971
    )
1972
    with open(self._server_key, 'wb') as server_key_file:
Vincent Pelletier's avatar
Vincent Pelletier committed
1973 1974 1975
      server_key_file.write(key_pem)
      server_key_file.write(utils.dump_certificate(
        self._setCertificateRemainingLifeTime(
1976
          key=utils.load_privatekey(utils.toBytes(http_cas_key)),
Vincent Pelletier's avatar
Vincent Pelletier committed
1977 1978 1979
          crt=utils.load_certificate(
            crt_pem,
            [