cli.py 29.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 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 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 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 824 825 826 827 828 829 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 862 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 889 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 977 978 979 980 981 982
# This file is part of caucase
# Copyright (C) 2017-2018  Nexedi
#     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
"""
from __future__ import absolute_import, print_function
import argparse
from binascii import hexlify
import datetime
import httplib
import json
import os
import socket
import struct
import sys
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from . import exceptions
from . import utils
from . import version
from .client import (
  CaucaseError,
  CaucaseClient,
  HTTPSOnlyCaucaseClient,
)

class RetryingCaucaseClient(CaucaseClient):
  """
  Similar to CaucaseClient, but retries indefinitely on http & socket errors.
  To use in long-lived processes where server may not be available yet, or is
  (hopefuly) temporarily unavailable, etc.

  Retries every 10 seconds.
  """
  _until = staticmethod(utils.until)
  _log_file = sys.stdout

  def _request(self, connection, method, url, body=None, headers=None):
    while True:
      try:
        return super(RetryingCaucaseClient, self)._request(
          connection=connection,
          method=method,
          url=url,
          body=body,
          headers=headers,
        )
      except (
        socket.error,
        # Note: all exceptions below inherit from httplib.HTTPException,
        # but so do errors which are either sign of code bugs
        # (ImproperConnectionState) or sign of garbage values provided by
        # caller/user, and these should be let through.
        httplib.BadStatusLine,
        httplib.LineTooLong,
        httplib.UnknownProtocol,
        httplib.IncompleteRead,
        ) as exception:
        connection.close() # Resets HTTPConnection state machine.
        # Note: repr(str(exception)) is nicer than repr(exception), without
        # letting non-printable characters through.
        print(
          'Got a network error, retrying in a bit: %s: %r' % (
            exception.__class__.__name__,
            str(exception),
          ),
          file=self._log_file,
        )
        self._until(datetime.datetime.now() + datetime.timedelta(0, 10))

_cryptography_backend = default_backend()

STATUS_ERROR = 1
STATUS_WARNING = 2
STATUS_CALLBACK_ERROR = 3

MODE_SERVICE = 'service'
MODE_USER = 'user'

class CLICaucaseClient(object):
  """
  CLI functionalities
  """
  # Note: this class it more to reduce local variable scopes (avoiding
  # accidental mixups) in each methods than about API declaration.

  def __init__(self, client):
    self._client = client

  def putCSR(self, csr_path_list):
    """
    --send-csr
    """
    for csr_path in csr_path_list:
      csr_pem = utils.getCertRequest(csr_path)
      # Quick sanity check
      utils.load_certificate_request(csr_pem)
      print(
        self._client.createCertificateSigningRequest(csr_pem),
        utils.toBytes(csr_path),
      )

  def getCSR(self, csr_id_path_list):
    """
    --get-csr
    """
    for csr_id, csr_path in csr_id_path_list:
      csr_pem = self._client.getCertificateSigningRequest(int(csr_id))
      with open(csr_path, 'ab') as csr_file:
        csr_file.write(csr_pem)

  def getCRT(self, warning, error, crt_id_path_list, ca_list):
    """
    --get-crt
    """
    for crt_id, crt_path in crt_id_path_list:
      crt_id = int(crt_id)
      try:
        crt_pem = self._client.getCertificate(crt_id)
      except CaucaseError as e:
        if e.args[0] != httplib.NOT_FOUND:
          raise
        try:
          self._client.getCertificateSigningRequest(crt_id)
        except CaucaseError as e:
          if e.args[0] != httplib.NOT_FOUND:
            raise
          print(crt_id, b'not found - maybe CSR was rejected ?')
          error = True
        else:
          print(crt_id, b'CSR still pending')
          warning = True
      else:
        print(crt_id, end=' ')
        if utils.isCertificateAutoSigned(utils.load_certificate(
          crt_pem,
          ca_list,
          None,
        )):
          print(b'was (originally) automatically approved')
        else:
          print(b'was (originally) manually approved')
        if os.path.exists(crt_path):
          try:
            key_pem = utils.getKey(crt_path)
          except ValueError:
            print(
              b'Expected to find exactly one privatekey key in %s, skipping' % (
                crt_path,
              ),
              file=sys.stderr,
            )
            error = True
            continue
          try:
            utils.validateCertAndKey(crt_pem, key_pem)
          except ValueError:
            print(
              b'Key in %s does not match retrieved certificate, skipping',
              file=sys.stderr,
            )
            error = True
            continue
        with open(crt_path, 'ab') as crt_file:
          crt_file.write(crt_pem)
    return warning, error

  def revokeCRT(self, error, crt_key_list):
    """
    --revoke-crt
    """
    for crt_path, key_path in crt_key_list:
      try:
        crt, key, _ = utils.getKeyPair(crt_path, key_path)
      except ValueError:
        print(
          b'Could not find (exactly) one matching key pair in %s, skipping' % (
            [x for x in set((crt_path, key_path)) if x],
          ),
          file=sys.stderr,
        )
        error = True
        continue
      self._client.revokeCertificate(crt, key)
    return error

  def renewCRT(
    self,
    crt_key_list,
    renewal_deadline,
    key_len,
    ca_certificate_list,
    updated,
    error,
  ):
    """
    --renew-crt
    """
    for crt_path, key_path in crt_key_list:
      try:
        old_crt_pem, old_key_pem, key_path = utils.getKeyPair(
          crt_path,
          key_path,
        )
      except ValueError:
        print(
          b'Could not find (exactly) one matching key pair in %s, skipping' % (
            [x for x in set((crt_path, key_path)) if x],
          ),
          file=sys.stderr,
        )
        error = True
        continue
      try:
        old_crt = utils.load_certificate(
          old_crt_pem,
          ca_certificate_list,
          None,
        )
      except exceptions.CertificateVerificationError:
        print(
          crt_path,
          b'was not signed by this CA, revoked or otherwise invalid, skipping',
        )
        continue
      if renewal_deadline < old_crt.not_valid_after:
        print(crt_path, b'did not reach renew threshold, not renewing')
        continue
      new_key_pem, new_crt_pem = self._client.renewCertificate(
        old_crt=old_crt,
        old_key=utils.load_privatekey(old_key_pem),
        key_len=key_len,
      )
      if key_path is None:
        with open(crt_path, 'wb') as crt_file:
          crt_file.write(new_key_pem)
          crt_file.write(new_crt_pem)
      else:
        with open(
          crt_path,
          'wb',
        ) as crt_file, open(
          key_path,
          'wb',
        ) as key_file:
          key_file.write(new_key_pem)
          crt_file.write(new_crt_pem)
      updated = True
    return updated, error

  def listCSR(self, mode):
    """
    --list-csr
    """
    print(b'-- pending', mode, b'CSRs --')
    print(
      b'%20s | %s' % (
        b'csr_id',
        b'subject preview (fetch csr and check full content !)',
      ),
    )
    for entry in self._client.getPendingCertificateRequestList():
      csr = utils.load_certificate_request(utils.toBytes(entry['csr']))
      print(
        b'%20s | %r' % (
          utils.toBytes(entry['id']),
          utils.toBytes(repr(csr.subject)),
        ),
      )
    print(b'-- end of pending', mode, b'CSRs --')

  def signCSR(self, csr_id_list):
    """
    --sign-csr
    """
    for csr_id in csr_id_list:
      self._client.createCertificate(int(utils.toUnicode(csr_id)))

  def signCSRWith(self, csr_id_path_list):
    """
    --sign-csr-with
    """
    for csr_id, csr_path in csr_id_path_list:
      self._client.createCertificate(
        int(utils.toUnicode(csr_id)),
        template_csr=utils.getCertRequest(csr_path),
      )

  def rejectCSR(self, csr_id_list):
    """
    --reject-csr
    """
    for csr_id in csr_id_list:
      self._client.deletePendingCertificateRequest(int(csr_id))

  def revokeOtherCRT(self, crt_list):
    """
    --revoke-other-crt
    """
    error = False
    for crt_path in crt_list:
      try:
        # Note: also raises when there are serveral certs. This is intended:
        # revoking many certs from a single file seems a dubious use-case
        # (especially in the automated issuance context, which is supposed to
        # be caucase's main target), with high risk if carried without
        # questions (too many certificates revoked, or asingle unexpected one
        # among these, ...) and unambiguous solution is easy (if a human is
        # involved, as is likely the case, more or less directly, for
        # authenticated revocations).
        crt_pem = utils.getCert(crt_path)
      except ValueError:
        print(
          b'Could not load a single certificate in %s, skipping' % (
            crt_path,
          ),
          file=sys.stderr,
        )
      self._client.revokeCertificate(crt_pem)
    return error

  def revokeSerial(self, serial_list):
    """
    --revoke-serial
    """
    for serial in serial_list:
      self._client.revokeSerial(serial)

def main(argv=None):
  """
  Command line caucase client entry point.
  """
  parser = argparse.ArgumentParser(
    description='caucase',
    version=version.__version__,
  )
  # XXX: currently, it is the server which chooses which digest is used to sign
  # stuff.
  # Should clients be able to tell it how to sign (and server could reject) ?
  parser.add_argument(
    '--ca-url',
    required=True,
    metavar='URL',
    help='caucase service HTTP base URL.',
  )
  parser.add_argument(
    '--ca-crt',
    default='cas.crt.pem',
    metavar='CRT_PATH',
    help='Services CA certificate file location. default: %(default)s',
  )
  parser.add_argument(
    '--user-ca-crt',
    default='cau.crt.pem',
    metavar='CRT_PATH',
    help='Users CA certificate file location. default: %(default)s',
  )
  parser.add_argument(
    '--crl',
    default='cas.crl.pem',
    metavar='CRL_PATH',
    help='Services certificate revocation list location. default: %(default)s',
  )
  parser.add_argument(
    '--user-crl',
    default='cau.crl.pem',
    metavar='CRL_PATH',
    help='Users certificate revocation list location. default: %(default)s',
  )
  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',
  )
  parser.add_argument(
    '--on-renew',
    metavar='EXECUTABLE_PATH',
    help='Path of an executable file to call after any renewal (CA cert, '
    'certificate, revocation list).',
  )
  parser.add_argument(
    '--user-key',
    metavar='KEY_PATH',
    help='User private key and certificate bundled in a single file to '
    'authenticate with caucase.',
  )
  parser.add_argument(
    '--mode',
    default=MODE_SERVICE,
    choices=[MODE_SERVICE, MODE_USER],
    help='The type of certificates you want to manipulate: '
    '<%s> certificates allow managing caucase server, '
    '<%s> certificates can be validated by caucase\'s CA certificate. '
    'default: %%(default)s' % (
      MODE_USER,
      MODE_SERVICE,
    )
  )

  anonymous_group = parser.add_argument_group(
    'Anonymous actions',
    'Actions which do no require authentication.',
  )
  anonymous_group.add_argument(
    '--send-csr',
    nargs='+',
    metavar='CSR_PATH',
    default=[],
    help='Request signature of these certificate signing requests.',
  )
  anonymous_group.add_argument(
    '--get-crt',
    nargs=2,
    action='append',
    default=[],
    metavar=('CSR_ID', 'CRT_PATH'),
    help='Retrieve the certificate identified by '
    'identifier and store it at given path. '
    'If CRT_PATH exists and contains the private key corresponding to '
    'received certificate, certificate will be appended to that file. '
    'Can be given multiple times.',
  )
  anonymous_group.add_argument(
    '--revoke-crt',
    nargs=2,
    action='append',
    default=[],
    metavar=('CRT_PATH', 'KEY_PATH'),
    help='Revoke certificate. If CRT_PATH file contains both a certificate '
    'and a key, KEY_PATH is ignored. '
    'Can be given multiple times.',
  )
  anonymous_group.add_argument(
    '--renew-crt',
    nargs=2,
    default=[],
    action='append',
    metavar=('CRT_PATH', 'KEY_PATH'),
    help='Renew certificates in-place if they exceed THRESHOLD. '
    'If CRT_PATH file contains both certificate and key, KEY_PATH is ignored '
    'and CRT_PATH receives both the new key and the new certificate. '
    'Can be given multiple times.',
  )
  anonymous_group.add_argument(
    '--get-csr',
    nargs=2,
    default=[],
    action='append',
    metavar=('CSR_ID', 'CSR_PATH'),
    help='Retrieve certificate signing request and append to CSR_PATH. '
    'Should only be needed before deciding to sign or reject the request. '
    'Can be given multiple times.',
  )
  anonymous_group.add_argument(
    '--update-user',
    action='store_true',
    help='Update or create user CA and CRL. '
    'Should only be needed by the https server in front of caucase.'
  )

  authenticated_group = parser.add_argument_group(
    'Authenticated actions',
    'Actions which require an authentication. Requires --user-key .',
  )
  authenticated_group.add_argument(
    '--list-csr',
    action='store_true',
    help='List certificate signing requests currently pending on server.',
  )
  authenticated_group.add_argument(
    '--sign-csr',
    nargs='+',
    default=[],
    metavar='CSR_ID',
    help='Sign pending certificate signing requests.',
  )
  authenticated_group.add_argument(
    '--sign-csr-with',
    nargs=2,
    default=[],
    action='append',
    metavar=('CSR_ID', 'CSR_PATH'),
    help='Sign pending certificate signing request, but use provided CSR for '
    'requested subject and extensions instead of stored CSR. '
    'Can be given multiple times.',
  )
  authenticated_group.add_argument(
    '--reject-csr',
    nargs='+',
    default=[],
    metavar='CSR_ID',
    help='Reject these pending certificate signing requests.',
  )
  authenticated_group.add_argument(
    '--revoke-other-crt',
    nargs='+',
    default=[],
    metavar='CRT_PATH',
    help='Revoke certificate without needing access to their private key.'
  )
  authenticated_group.add_argument(
    '--revoke-serial',
    nargs='+',
    default=[],
    metavar='SERIAL',
    type=int,
    help='Revoke certificate by serial number, without needing the '
    'certificate at all. DANGEROUS: typos will not be detected ! '
    'COSTLY: revocation will stay in the revocation list until all '
    'currently valid CA certificates have expired. '
    'Use --revoke and --revoke-other-crt whenever possible.',
  )
  args = parser.parse_args(argv)

  sign_csr_id_set = set(args.sign_csr)
  sign_with_csr_id_set = {x for x, _ in args.sign_csr_with}
  if (
    sign_csr_id_set.intersection(args.reject_csr) or
    sign_with_csr_id_set.intersection(args.reject_csr) or
    sign_csr_id_set.intersection(sign_with_csr_id_set)
  ):
    print(
      b'A given CSR_ID cannot be in more than one of --sign-csr, '
      b'--sign-csr-with and --reject-csr',
      file=sys.stderr,
    )
    raise SystemExit(STATUS_ERROR)

  updated = False
  warning = False
  error = False
  finished = False
  cau_url = args.ca_url + '/cau'
  cas_url = args.ca_url + '/cas'

  try:
    # Get a working, up-to-date CAS CA certificate file.
    updated |= CaucaseClient.updateCAFile(cas_url, args.ca_crt)
    # --update-user, CA part
    if args.update_user or args.mode == MODE_USER:
      updated |= CaucaseClient.updateCAFile(cau_url, args.user_ca_crt)

    client = CLICaucaseClient(
      client=CaucaseClient(
        ca_url={
          MODE_SERVICE: cas_url,
          MODE_USER: cau_url,
        }[args.mode],
        ca_crt_pem_list=utils.getCertList(args.ca_crt),
        user_key=args.user_key,
      ),
    )
    ca_list = [
      utils.load_ca_certificate(x)
      for x in utils.getCertList({
        MODE_SERVICE: args.ca_crt,
        MODE_USER: args.user_ca_crt,
      }[args.mode])
    ]
    client.putCSR(args.send_csr)
    client.getCSR(args.get_csr)
    warning, error = client.getCRT(warning, error, args.get_crt, ca_list)
    error = client.revokeCRT(error, args.revoke_crt)
    updated, error = client.renewCRT(
      crt_key_list=args.renew_crt,
      renewal_deadline=datetime.datetime.utcnow() + datetime.timedelta(
        args.threshold,
        0,
      ),
      key_len=args.key_len,
      ca_certificate_list=ca_list,
      updated=updated,
      error=error,
    )
    client.signCSR(args.sign_csr)
    client.signCSRWith(args.sign_csr_with)
    client.rejectCSR(args.reject_csr)
    error |= client.revokeOtherCRT(args.revoke_other_crt)
    client.revokeSerial(args.revoke_serial)
    # show latest CSR list status
    if args.list_csr:
      client.listCSR(args.mode)
    # update our CRL after all revocations we were requested
    updated |= CaucaseClient.updateCRLFile(cas_url, args.crl, [
      utils.load_ca_certificate(x)
      for x in utils.getCertList(args.ca_crt)
    ])
    # --update-user, CRL part
    if args.update_user:
      updated |= CaucaseClient.updateCRLFile(cau_url, args.user_crl, [
        utils.load_ca_certificate(x)
        for x in utils.getCertList(args.user_ca_crt)
      ])
    finished = True
  finally:
    if updated and args.on_renew:
      status = os.system(args.on_renew)
      # Avoid raising if we arrived here because of an exception, to not hide
      # the original problem.
      if finished and status:
        raise SystemExit(STATUS_CALLBACK_ERROR)
  if error:
    raise SystemExit(STATUS_ERROR)
  if warning:
    raise SystemExit(STATUS_WARNING)

def probe(argv=None):
  """
  Verify basic caucase server functionality
  """
  parser = argparse.ArgumentParser(
    description='caucase probe - Verify basic caucase server functionality',
    version=version.__version__,
  )
  parser.add_argument(
    'ca_url',
    nargs=1,
    help='caucase service HTTP base URL.',
  )
  ca_url, = parser.parse_args(argv).ca_url
  cas_url = ca_url + '/cas'
  http_client = CaucaseClient(
    ca_url=cas_url,
  )
  http_ca_pem = http_client.getCACertificate()
  https_ca_pem = HTTPSOnlyCaucaseClient(
    ca_url=cas_url,
    ca_crt_pem_list=[http_ca_pem],
  ).getCACertificate()
  # Retrieve again in case there was a renewal between both calls - we do
  # not expect 2 renewals in very short succession.
  http2_ca_pem = http_client.getCACertificate()
  if https_ca_pem not in (http_ca_pem, http2_ca_pem):
    raise ValueError('http and https do not serve the same caucase database')

def updater(argv=None, until=utils.until):
  """
  Bootstrap certificate and companion files and keep them up-to-date.
  """
  parser = argparse.ArgumentParser(
    description='caucase updater - '
    'Bootstrap certificate and companion files and keep them up-to-date',
    version=version.__version__,
  )
  parser.add_argument(
    '--ca-url',
    required=True,
    metavar='URL',
    help='caucase service HTTP base URL.',
  )
  parser.add_argument(
    '--cas-ca',
    required=True,
    metavar='CRT_PATH',
    help='Service CA certificate file location used to verify connection '
    'to caucase. Will be maintained up-to-date. '
    'default: %(default)s',
  )
  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',
  )
  parser.add_argument(
    '--on-renew',
    metavar='EXECUTABLE_PATH',
    help='Path of an executable file to call after any renewal (CA cert, '
    'certificate, revocation list).',
  )
  parser.add_argument(
    '--max-sleep',
    default=31,
    type=float,
    help='Maximum number of days to sleep for. Allows refreshing the CRL '
    'more often on sensitive services. default: %(default)s',
  )
  parser.add_argument(
    '--mode',
    default=MODE_SERVICE,
    choices=[MODE_SERVICE, MODE_USER],
    help='The type of certificates you want to manipulate: '
    '<%s> certificates allow managing caucase server, '
    '<%s> certificates can be validated by caucase\'s CA certificate. '
    'default: %%(default)s' % (
      MODE_USER,
      MODE_SERVICE,
    )
  )
  parser.add_argument(
    '--csr',
    metavar='CSR_PATH',
    help='Path of your CSR to use for initial request of a certificate for '
    'MODE. Ignored once a certificate exists at the location given by '
    '--crt .',
  )
  parser.add_argument(
    '--key',
    metavar='KEY_PATH',
    help='Path of your private key file. Must always exist when this command '
    'is started. Will be updated on certificate renewal. If not provided, '
    'both key and certificate will be stored in the file pointed at by '
    '--crt .',
  )
  parser.add_argument(
    '--crt',
    metavar='CRT_PATH',
    help='Path of your certificate for MODE. Will be renewed before '
    'expiration.',
  )
  parser.add_argument(
    '--ca',
    required=True,
    metavar='CRT_PATH',
    help='Path of your CA certificate for MODE. '
    'Will be maintained up-to-date.'
  )
  parser.add_argument(
    '--crl',
    required=True,
    metavar='CRT_PATH',
    help='Path of your certificate revocation list for MODE. '
    'Will be maintained up-to-date.'
  )
  args = parser.parse_args(argv)
  try:
    cas_url = args.ca_url + '/cas'
    ca_url = {
      MODE_SERVICE: cas_url,
      MODE_USER: args.ca_url + '/cau',
    }[args.mode]
    threshold = datetime.timedelta(args.threshold, 0)
    max_sleep = datetime.timedelta(args.max_sleep, 0)
    updated = RetryingCaucaseClient.updateCAFile(
      cas_url,
      args.cas_ca,
    ) and args.cas_ca == args.ca
    client = RetryingCaucaseClient(
      ca_url=ca_url,
      ca_crt_pem_list=utils.getCertList(args.cas_ca)
    )
    if args.crt and not utils.hasOneCert(args.crt):
      print(b'Bootstraping...')
      csr_pem = utils.getCertRequest(args.csr)
      # Quick sanity check before bothering server
      utils.load_certificate_request(csr_pem)
      csr_id = client.createCertificateSigningRequest(csr_pem)
      print(b'Waiting for signature of', csr_id)
      while True:
        try:
          crt_pem = client.getCertificate(csr_id)
        except CaucaseError as e:
          if e.args[0] != httplib.NOT_FOUND:
            raise
          # If server does not know our CSR anymore, getCSR will raise.
          # If it does, we were likely rejected, so exit by letting exception
          # through.
          client.getCertificateSigningRequest(csr_id)
          # Still here ? Ok, wait a bit and try again.
          until(datetime.datetime.utcnow() + datetime.timedelta(0, 60))
        else:
          with open(args.crt, 'ab') as crt_file:
            crt_file.write(crt_pem)
          updated = True
          break
      print(b'Bootstrap done')
    next_deadline = datetime.datetime.utcnow()
    while True:
      print(
        b'Next wake-up at',
        next_deadline.strftime(b'%Y-%m-%d %H:%M:%S +0000'),
      )
      now = until(next_deadline)
      next_deadline = now + max_sleep
      if args.cas_ca != args.ca and RetryingCaucaseClient.updateCAFile(
        cas_url,
        args.cas_ca,
      ):
        client = RetryingCaucaseClient(
          ca_url=ca_url,
          ca_crt_pem_list=utils.getCertList(args.cas_ca)
        )
      if RetryingCaucaseClient.updateCAFile(ca_url, args.ca):
        print(b'Got new CA')
        updated = True
        # Note: CRL expiration should happen several time during CA renewal
        # period, so it should not be needed to keep track of CA expiration
        # for next deadline.
      ca_crt_list = [
        utils.load_ca_certificate(x)
        for x in utils.getCertList(args.ca)
      ]
      if RetryingCaucaseClient.updateCRLFile(ca_url, args.crl, ca_crt_list):
        print(b'Got new CRL')
        updated = True
        with open(args.crl, 'rb') as crl_file:
          next_deadline = min(
            next_deadline,
            utils.load_crl(crl_file.read(), ca_crt_list).next_update,
          )
      if args.crt:
        crt_pem, key_pem, key_path = utils.getKeyPair(args.crt, args.key)
        crt = utils.load_certificate(crt_pem, ca_crt_list, None)
        if crt.not_valid_after - threshold <= now:
          print(b'Renewing', args.crt)
          new_key_pem, new_crt_pem = client.renewCertificate(
            old_crt=crt,
            old_key=utils.load_privatekey(key_pem),
            key_len=args.key_len,
          )
          if key_path is None:
            with open(args.crt, 'wb') as crt_file:
              crt_file.write(new_key_pem)
              crt_file.write(new_crt_pem)
          else:
            with open(
              args.crt,
              'wb',
            ) as crt_file, open(
              key_path,
              'wb',
            ) as key_file:
              key_file.write(new_key_pem)
              crt_file.write(new_crt_pem)
          crt = utils.load_certificate(utils.getCert(args.crt), ca_crt_list, None)
          updated = True
        next_deadline = min(
          next_deadline,
          crt.not_valid_after - threshold,
        )
      if updated:
        if args.on_renew is not None:
          status = os.system(args.on_renew)
          if status:
            print(b'Renewal hook exited with status:', status, file=sys.stderr)
            raise SystemExit(STATUS_ERROR)
        updated = False
  except (utils.SleepInterrupt, SystemExit):
    # Not intercepting KeyboardInterrupt so interrupting outside of
    # interruptibleSleep shows where the script got interrupted.
    pass

def rerequest(argv=None):
  """
  Produce a new private key and sign a CSR created by copying an existing,
  well-signed CSR.
  """
  parser = argparse.ArgumentParser(
    description='caucase rerequest - '
    'Produce a new private key and sign a CSR created by copying an existing, '
    'well-signed CSR.',
    version=version.__version__,
  )
  parser.add_argument(
    '--template',
    required=True,
    help='Existing PEM-encodd CSR to use as a template.',
  )
  parser.add_argument(
    '--csr',
    required=True,
    help='Path of produced PEM-encoded CSR.',
  )
  parser.add_argument(
    '--key',
    required=True,
    help='Path of produced PEM-encoded private key.',
  )
  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',
  )
  args = parser.parse_args(argv)
  template = utils.load_certificate_request(
    utils.getCertRequest(args.template),
  )
  key = utils.generatePrivateKey(key_len=args.key_len)
  csr_pem = utils.dump_certificate_request(
    x509.CertificateSigningRequestBuilder(
      subject_name=template.subject,
      extensions=template.extensions,
    ).sign(
      private_key=key,
      algorithm=utils.DEFAULT_DIGEST_CLASS(),
      backend=_cryptography_backend,
    ),
  )
  key_pem = utils.dump_privatekey(key)
  orig_umask = os.umask(0o177)
  try:
    with open(args.key, 'wb') as key_file:
      key_file.write(key_pem)
  finally:
    os.umask(orig_umask)
  with open(args.csr, 'wb') as csr_file:
    csr_file.write(csr_pem)

def key_id(argv=None):
  """
  Displays key identifier from private key, and the list of acceptable key
  identifiers for a given backup file.
  """
  parser = argparse.ArgumentParser(
    description='caucase key id - '
    'Displays key identifier from private key, and the list of acceptable key'
    'identifiers for a given backup file.',
    version=version.__version__,
  )
  parser.add_argument(
    '--private-key',
    nargs='+',
    default=(),
    help='PEM-encoded keys to display the identifier of.',
  )
  parser.add_argument(
    '--backup',
    nargs='+',
    default=(),
    help='Caucase backup files to display acceptable deciphering key '
    'identifiers of.',
  )
  args = parser.parse_args(argv)
  for key_path in args.private_key:
    with open(key_path, 'rb') as key_file:
      print(
        key_path,
        hexlify(
          x509.SubjectKeyIdentifier.from_public_key(
            utils.load_privatekey(key_file.read()).public_key(),
          ).digest,
        ),
      )
  for backup_path in args.backup:
    print(backup_path)
    with open(backup_path, 'rb') as backup_file:
      magic = backup_file.read(8)
      if magic != b'caucase\0':
        raise ValueError('Invalid backup magic string')
      header_len, = struct.unpack(
        '<I',
        backup_file.read(struct.calcsize('<I')),
      )
      for key_entry in json.loads(backup_file.read(header_len))['key_list']:
        print(b' ', key_entry['id'].encode('utf-8'))