storage.py 18.7 KB
Newer Older
1
# This file is part of caucase
2
# Copyright (C) 2017-2020  Nexedi SA
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.
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.
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
"""
from __future__ import absolute_import
from random import getrandbits
26
import os
Vincent Pelletier's avatar
Vincent Pelletier committed
27 28 29
import sqlite3
from threading import local
from time import time
30 31
from cryptography import x509
from cryptography.hazmat.backends import default_backend
Vincent Pelletier's avatar
Vincent Pelletier committed
32
from .exceptions import NoStorage, NotFound, Found
33
from .utils import toBytes, toUnicode, datetime2timestamp
Vincent Pelletier's avatar
Vincent Pelletier committed
34 35 36

__all__ = ('SQLite3Storage', )

37
_cryptography_backend = default_backend()
Vincent Pelletier's avatar
Vincent Pelletier committed
38
DAY_IN_SECONDS = 60 * 60 * 24
39

40
class NoReentryConnection(sqlite3.Connection):
41 42 43 44 45 46
  """
  Refuse to start an already started transaction.

  Allows detecting code bugs which would lead to non-atomic updates (partial
  outer transaction getting committed by an inner transaction).
  """
47 48 49
  __entered = False

  def __enter__(self):
50
    if self.__entered: # pragma: no cover
51 52 53 54 55 56 57 58
      raise Exception('Subtransactions are not supported')
    self.__entered = True
    return super(NoReentryConnection, self).__enter__()

  def __exit__(self, exc_type, exc_value, traceback):
    self.__entered = False
    return super(NoReentryConnection, self).__exit__(exc_type, exc_value, traceback)

Vincent Pelletier's avatar
Vincent Pelletier committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72
class SQLite3Storage(local):
  """
  CA data storage.

  Every cryptographic type this class deals with must be PEM-encoded.
  """
  def __init__(
    self,
    db_path,
    table_prefix,
    max_csr_amount=50,
    crt_keep_time=1,
    crt_read_keep_time=0.05, # About 1 hour
    enforce_unique_key_id=False,
73
    mode=0o600,
Vincent Pelletier's avatar
Vincent Pelletier committed
74
  ):
75
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    db_path (str)
      SQLite connection string.
    table_prefix (str)
      Name to use as a prefix for all tables managed by this storage adapter.
      Allows sharing the database, although it should only be within the same
      caucase process for access permission reasons.
    max_csr_amount (int)
      Maximum number of allowed pending certificate signing requests.
      To prevent flood.
    crt_keep_time (float)
      Time to keep signed certificates for, in days.
    crt_read_keep_time (float)
      Time to keep CRT content for after it was first read, in days.
      Allows requester to fail retrieving the certificate by tolerating
      retries.
    enforce_unique_key_id (bool)
      When true, certificate requests cannot be appended if there is already
      and known entry for the same private key.
      Note: this only makes sense if crt_keep_time and crt_read_keep_time are
      set at least to the certificate life span.
      Useful for backups, to ensure the certificate to revoke can be uniquely
      identified from the key used to decrypt the backup archive.
98 99
    mode (int)
      Permissions of the main database file upon creation.
100
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
101
    super(SQLite3Storage, self).__init__()
102 103 104 105 106 107
    # Create database file if it does not exist, so mode can be controlled.
    os.close(os.open(
      db_path,
      os.O_CREAT | os.O_RDONLY,
      mode,
    ))
108
    self._db = db = sqlite3.connect(db_path, factory=NoReentryConnection)
Vincent Pelletier's avatar
Vincent Pelletier committed
109 110 111 112 113 114 115 116 117 118
    self._table_prefix = table_prefix
    db.row_factory = sqlite3.Row
    self._max_csr_amount = max_csr_amount
    self._crt_keep_time = crt_keep_time * DAY_IN_SECONDS
    self._crt_read_keep_time = crt_read_keep_time * DAY_IN_SECONDS
    with db:
      # Note about revoked.serial: certificate serials exceed the 63 bits
      # sqlite can accept as integers, so store these as text. Use a trivial
      # string serialisation: not very space efficient, but this should not be
      # a limiting issue for our use-cases anyway.
119 120
      c = db.cursor()
      c.executescript('''
Vincent Pelletier's avatar
Vincent Pelletier committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
        CREATE TABLE IF NOT EXISTS %(prefix)sca (
          expiration_date INTEGER,
          key TEXT,
          crt TEXT
        );
        CREATE TABLE IF NOT EXISTS %(prefix)scrt (
          id INTEGER PRIMARY KEY,
          key_id TEXT %(key_id_constraint)s,
          expiration_date INTEGER,
          csr TEXT,
          crt TEXT
        );
        CREATE TABLE IF NOT EXISTS %(prefix)srevoked (
          serial TEXT PRIMARY KEY,
          revocation_date INTEGER,
          expiration_date INTEGER
        );
        CREATE TABLE IF NOT EXISTS %(prefix)scounter (
          name TEXT PRIMARY KEY,
          value INTEGER
        );
        CREATE TABLE IF NOT EXISTS %(prefix)sconfig_once (
          name TEXT PRIMARY KEY,
          value TEXT
145
        );
146 147 148 149
        CREATE TABLE IF NOT EXISTS %(prefix)sconfig (
          name TEXT PRIMARY KEY,
          value TEXT
        );
Vincent Pelletier's avatar
Vincent Pelletier committed
150 151 152 153
      ''' % {
        'prefix': table_prefix,
        'key_id_constraint': 'UNIQUE' if enforce_unique_key_id else '',
      })
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
      try:
        crl_row = self._executeSingleRow(
          'SELECT crl FROM %(prefix)scrl '
          'ORDER BY expiration_date DESC LIMIT 1',
        )
      except sqlite3.OperationalError as exc:
        # XXX: no error codes in sqlite and only a generic error class ?
        if not exc.args[0].startswith('no such table: '): # pragma: no cover
          raise
        crl_row = None
      if crl_row is not None:
        self._setConfig(
          'crl_last_update',
          str(datetime2timestamp(x509.load_pem_x509_crl(
            toBytes(crl_row['crl']),
            _cryptography_backend,
          ).last_update)),
        )
        self._execute(c, 'DROP TABLE IF EXISTS %(prefix)scrl')
173

174 175 176 177 178 179 180 181
  def _execute(self, cursor, sql, parameters=()):
    return cursor.execute(
      sql % {
        'prefix': self._table_prefix,
      },
      parameters,
    )

Vincent Pelletier's avatar
Vincent Pelletier committed
182 183 184 185 186 187 188
  def _incrementCounter(self, name, increment=1, initial=0):
    """
    Increment counter with <name> by <increment> and return resulting value.
    If <name> is not found, it is created with <initial>, and then incremented.
    Does not commit.
    """
    row = self._executeSingleRow(
189
      'SELECT value FROM %(prefix)scounter WHERE name = ? LIMIT 2',
Vincent Pelletier's avatar
Vincent Pelletier committed
190 191 192 193 194 195 196
      (name, ),
    )
    if row is None:
      value = initial
    else:
      value = row['value']
    value += increment
197 198 199
    self._execute(
      self._db.cursor(),
      'INSERT OR REPLACE INTO %(prefix)scounter (name, value) VALUES (?, ?)',
Vincent Pelletier's avatar
Vincent Pelletier committed
200 201 202
      (name, value),
    )
    return value
203

Vincent Pelletier's avatar
Vincent Pelletier committed
204
  def _executeSingleRow(self, sql, parameters=()):
205
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
206
    Execute <sql>, raise if it produces more than 1 row, and return it.
207
    """
208
    result_list = self._execute(self._db.cursor(), sql, parameters).fetchall()
Vincent Pelletier's avatar
Vincent Pelletier committed
209 210 211
    if result_list:
      result, = result_list
      return result
212
    return None
213

Vincent Pelletier's avatar
Vincent Pelletier committed
214 215 216 217 218 219 220
  def getConfigOnce(self, name, default):
    """
    Retrieve the value of <name> from config-once list, or <default> if not
    stored.
    """
    with self._db:
      result = self._executeSingleRow(
221
        'SELECT value FROM %(prefix)sconfig_once WHERE name = ?',
Vincent Pelletier's avatar
Vincent Pelletier committed
222 223 224 225 226
        (name, ),
      )
    if result is None:
      return default
    return result['value']
227

Vincent Pelletier's avatar
Vincent Pelletier committed
228 229 230 231 232 233 234
  def setConfigOnce(self, name, value):
    """
    Store <value> as <name> in config-once list, if it was not already stored.
    If it was already stored, do nothing.
    """
    try:
      with self._db as db:
235 236 237
        self._execute(
          db.cursor(),
          'INSERT INTO %(prefix)sconfig_once (name, value) VALUES (?, ?)',
Vincent Pelletier's avatar
Vincent Pelletier committed
238 239 240 241
          (name, value),
        )
    except sqlite3.IntegrityError:
      pass
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
  def _getConfig(self, name, default):
    """
    Retrieve the value of <name> from config list, or <default> if not
    stored.
    """
    result = self._executeSingleRow(
      'SELECT value FROM %(prefix)sconfig WHERE name = ?',
      (name, ),
    )
    if result is None:
      return default
    return result['value']

  def _setConfig(self, name, value):
    """
    Store <value> as <name> in config list, possibly overwriting an existing
    entry.
    """
    self._execute(
      self._db.cursor(),
      'INSERT OR REPLACE INTO %(prefix)sconfig (name, value) VALUES (?, ?)',
      (name, value),
    )

267
  def getCAKeyPairList(self, prune=True):
Vincent Pelletier's avatar
Vincent Pelletier committed
268 269 270 271 272 273
    """
    Return the chronologically sorted (oldest in [0], newest in [-1])
    certificate authority key pairs.
    """
    with self._db as db:
      c = db.cursor()
274
      if prune:
275 276 277
        self._execute(
          c,
          'DELETE FROM %(prefix)sca WHERE expiration_date < ?',
278 279
          (time(), ),
        )
Vincent Pelletier's avatar
Vincent Pelletier committed
280 281
      return [
        {
282 283
          'crt_pem': toBytes(x['crt']),
          'key_pem': toBytes(x['key']),
Vincent Pelletier's avatar
Vincent Pelletier committed
284
        }
285 286 287
        for x in self._execute(
          c,
          'SELECT key, crt FROM %(prefix)sca ORDER BY expiration_date ASC',
Vincent Pelletier's avatar
Vincent Pelletier committed
288 289
        ).fetchall()
      ]
290

Vincent Pelletier's avatar
Vincent Pelletier committed
291
  def appendCAKeyPair(self, expiration_timestamp, key_pair):
292 293
    """
    Store a certificate authority key pair.
Vincent Pelletier's avatar
Vincent Pelletier committed
294 295
    expiration_timestamp (int)
      Unix GMT timestamp of CA certificate "valid until" date.
296
    key_pair (dict with 'key_pem' and 'crt_pem' items)
Vincent Pelletier's avatar
Vincent Pelletier committed
297
      CA key pair to store, as bytes.
298
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
299
    with self._db as db:
300 301 302 303
      self._execute(
        db.cursor(),
        'INSERT INTO %(prefix)sca '
        '(expiration_date, key, crt) VALUES (?, ?, ?)',
Vincent Pelletier's avatar
Vincent Pelletier committed
304 305 306 307 308
        (
          expiration_timestamp,
          key_pair['key_pem'],
          key_pair['crt_pem'],
        ),
309 310
      )

Vincent Pelletier's avatar
Vincent Pelletier committed
311 312 313 314 315 316
  def appendCertificateSigningRequest(
    self,
    csr_pem,
    key_id,
    override_limits=False,
  ):
317
    """
318
    Store a certificate signing request and generate a unique ID for it.
Vincent Pelletier's avatar
Vincent Pelletier committed
319 320
    Note: ID uniqueness is only guaranteed among pending CSR, and may be reused
    after the original CSR has been discarded (by being rejected or signed).
321
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
322 323
    with self._db as db:
      known_csr = self._executeSingleRow(
324
        'SELECT id FROM %(prefix)scrt WHERE csr = ? LIMIT 2',
Vincent Pelletier's avatar
Vincent Pelletier committed
325 326 327 328 329 330 331 332 333 334 335
        (csr_pem, ),
      )
      if known_csr is not None:
        return known_csr['id'], None
      if override_limits:
        # Ignore max pending count
        # Do not increment the number of auto-signed certificates, but do not
        # automatically sign either.
        requested_count = None
      else:
        if self._executeSingleRow(
336
          'SELECT COUNT(*) FROM %(prefix)scrt WHERE crt IS NULL',
Vincent Pelletier's avatar
Vincent Pelletier committed
337 338 339 340 341
        )[0] >= self._max_csr_amount:
          raise NoStorage
        requested_count = self._incrementCounter('received_csr')
      csr_id = getrandbits(63)
      c = db.cursor()
342 343 344
      self._execute(
        c,
        'INSERT INTO %(prefix)scrt (id, key_id, csr) VALUES (?, ?, ?)',
Vincent Pelletier's avatar
Vincent Pelletier committed
345 346 347 348 349 350
        (
          csr_id,
          key_id,
          csr_pem,
        ),
      )
351 352 353
      self._execute(
        c,
        'DELETE FROM %(prefix)scrt WHERE expiration_date < ?',
Vincent Pelletier's avatar
Vincent Pelletier committed
354 355 356
        (time(), ),
      )
      return csr_id, requested_count
357

Vincent Pelletier's avatar
Vincent Pelletier committed
358
  def deletePendingCertificateSigningRequest(self, csr_id):
359
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
360 361 362 363 364 365
    Forget about a pending CSR. Does nothing if the CSR was already signed
    (it will be automatically garbage-collected later).
    Raises NotFound if there is no matching CSR.
    """
    with self._db as db:
      c = db.cursor()
366 367 368
      self._execute(
        c,
        'DELETE FROM %(prefix)scrt WHERE id = ? AND crt IS NULL',
Vincent Pelletier's avatar
Vincent Pelletier committed
369 370 371 372 373
        (csr_id, ),
      )
      if c.rowcount == 1:
        return
      raise NotFound
374

Vincent Pelletier's avatar
Vincent Pelletier committed
375 376 377
  def getCertificateSigningRequest(self, csr_id):
    """
    Retrieve a PEM-encoded certificate signing request.
378

Vincent Pelletier's avatar
Vincent Pelletier committed
379 380
    csr_id (int)
      Desired CSR id, as given when the CSR was stored.
381

Vincent Pelletier's avatar
Vincent Pelletier committed
382 383 384 385
    Raises NotFound if there is no matching CSR.
    """
    with self._db:
      result = self._executeSingleRow(
386
        'SELECT csr FROM %(prefix)scrt WHERE id = ?',
Vincent Pelletier's avatar
Vincent Pelletier committed
387 388 389 390
        (csr_id, ),
      )
      if result is None:
        raise NotFound
391
      return toBytes(result['csr'])
392

Vincent Pelletier's avatar
Vincent Pelletier committed
393 394 395
  def getCertificateSigningRequestList(self):
    """
    Return the list of all pending CSRs.
396

Vincent Pelletier's avatar
Vincent Pelletier committed
397 398 399 400 401
    Ignores any CSR for which a certificate was issued.
    """
    with self._db as db:
      return [
        {
402
          'id': str(x['id']),
403 404 405 406 407
          # XXX: because only call chain will end up serialising this value in
          # json, and for some reason python3 json module refuses bytes.
          # So rather than byte-ify (consistently with all PEM-encoded values)
          # to then have to unicode-ify, just unicode-ify here.
          'csr': toUnicode(x['csr']),
Vincent Pelletier's avatar
Vincent Pelletier committed
408
        }
409 410 411
        for x in self._execute(
          db.cursor(),
          'SELECT id, csr FROM %(prefix)scrt WHERE crt IS NULL',
Vincent Pelletier's avatar
Vincent Pelletier committed
412 413
        ).fetchall()
      ]
414

Vincent Pelletier's avatar
Vincent Pelletier committed
415 416 417
  def storeCertificate(self, csr_id, crt):
    """
    Store certificate for pre-existing CSR.
418

Vincent Pelletier's avatar
Vincent Pelletier committed
419 420 421 422 423
    Raises NotFound if there is no matching CSR, or if a certificate was
    already stored.
    """
    with self._db as db:
      c = db.cursor()
424 425 426 427
      self._execute(
        c,
        'UPDATE %(prefix)scrt SET crt=?, expiration_date = ? '
        'WHERE id = ? AND crt IS NULL',
Vincent Pelletier's avatar
Vincent Pelletier committed
428 429 430 431 432
        (
          crt,
          int(time() + self._crt_keep_time),
          csr_id,
        ),
433
      )
Vincent Pelletier's avatar
Vincent Pelletier committed
434 435
      if c.rowcount == 0:
        raise NotFound
436

Vincent Pelletier's avatar
Vincent Pelletier committed
437
  def getCertificate(self, crt_id):
438
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
439
    Retrieve a PEM-encoded certificate.
440

Vincent Pelletier's avatar
Vincent Pelletier committed
441 442
    crt_id (int)
      Desired certificate id, which is the same as corresponding CSR's id.
443

Vincent Pelletier's avatar
Vincent Pelletier committed
444 445
    Raises NotFound if there is no matching CRT or if no certificate was issued
    for it.
446
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
447 448
    with self._db as db:
      row = self._executeSingleRow(
449 450
        'SELECT crt, expiration_date FROM %(prefix)scrt '
        'WHERE id = ? AND crt IS NOT NULL',
Vincent Pelletier's avatar
Vincent Pelletier committed
451 452 453 454 455 456
        (crt_id, ),
      )
      if row is None:
        raise NotFound
      new_expiration_date = int(time() + self._crt_read_keep_time)
      if row['expiration_date'] > new_expiration_date:
457 458 459
        self._execute(
          db.cursor(),
          'UPDATE %(prefix)scrt SET expiration_date = ? WHERE id = ?',
Vincent Pelletier's avatar
Vincent Pelletier committed
460 461 462 463 464
          (
            new_expiration_date,
            crt_id,
          )
        )
465
      return toBytes(row['crt'])
Vincent Pelletier's avatar
Vincent Pelletier committed
466 467

  def getCertificateByKeyIdentifier(self, key_id):
468
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
469
    Return the certificate corresponding to given key_id.
470

Vincent Pelletier's avatar
Vincent Pelletier committed
471 472 473 474 475
    Raises NotFound if there is no matching CRT or if no certificate was issued
    for it.
    """
    with self._db:
      row = self._executeSingleRow(
476
        'SELECT crt FROM %(prefix)scrt WHERE key_id = ? AND crt IS NOT NULL',
Vincent Pelletier's avatar
Vincent Pelletier committed
477
        (key_id, ),
478
      )
Vincent Pelletier's avatar
Vincent Pelletier committed
479 480
      if row is None:
        raise NotFound
481
      return toBytes(row['crt'])
482

Vincent Pelletier's avatar
Vincent Pelletier committed
483
  def iterCertificates(self):
484
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
485
    Iterator over stored certificates.
486
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
487 488
    with self._db as db:
      c = db.cursor()
489 490 491 492
      self._execute(
        c,
        'SELECT crt FROM %(prefix)scrt WHERE crt IS NOT NULL',
      )
Vincent Pelletier's avatar
Vincent Pelletier committed
493 494 495 496
      while True:
        row = c.fetchone()
        if row is None:
          break
497
        yield toBytes(row['crt'])
Vincent Pelletier's avatar
Vincent Pelletier committed
498 499

  def revoke(self, serial, expiration_date):
500
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
501 502 503 504 505 506 507 508
    Add given certificate serial to the list of revoked certificates.
    Flushes any current CRL.

    serial (int)
      Serial of the certificate to revoke.
    expiration_date (int)
      Unix timestamp at which the certificate expires, allowing to remove this
      entry from the CRL.
509
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
510 511 512
    with self._db as db:
      c = db.cursor()
      try:
513 514 515
        self._execute(
          c,
          'INSERT INTO %(prefix)srevoked '
Vincent Pelletier's avatar
Vincent Pelletier committed
516
          '(serial, revocation_date, expiration_date) '
517
          'VALUES (?, ?, ?)',
Vincent Pelletier's avatar
Vincent Pelletier committed
518 519 520 521
          (
            str(serial),
            int(time()),
            expiration_date,
522
          ),
Vincent Pelletier's avatar
Vincent Pelletier committed
523 524 525
        )
      except sqlite3.IntegrityError:
        raise Found
526
      self._incrementCounter('crl_number')
527

528
  def getNextCertificateRevocationListNumber(self):
Vincent Pelletier's avatar
Vincent Pelletier committed
529
    """
530
    Get next CRL sequence number.
Vincent Pelletier's avatar
Vincent Pelletier committed
531 532
    """
    with self._db:
533
      return self._incrementCounter('crl_number')
534

535
  def storeCRLLastUpdate(self, last_update):
536
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
537
    Get next CRL sequence number.
538
    """
539 540
    with self._db:
      self._setConfig('crl_last_update', str(last_update))
541

542
  def storeCRLNumber(self, crl_number):
Vincent Pelletier's avatar
Vincent Pelletier committed
543
    """
544 545
    Set the current CRL sequence number.
    Use only when importing an existing CA.
Vincent Pelletier's avatar
Vincent Pelletier committed
546 547
    """
    with self._db as db:
548
      self._execute(
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
        db.cursor(),
        'INSERT OR REPLACE INTO %(prefix)scounter (name, value) VALUES (?, ?)',
        (
          'crl_number',
          crl_number,
        ),
      )

  def getCurrentCRLNumberAndLastUpdate(self):
    """
    Get the current CRL sequence number.
    """
    with self._db:
      last_update = self._getConfig('crl_last_update', None)
      return (
        # Note: does not increment the counter, but may set it to the default
        # value.
        self._incrementCounter('crl_number', increment=0),
Vincent Pelletier's avatar
Vincent Pelletier committed
567
        (
568 569 570
          last_update
          if last_update is None else
          int(last_update, 10)
Vincent Pelletier's avatar
Vincent Pelletier committed
571
        ),
572 573
      )

Vincent Pelletier's avatar
Vincent Pelletier committed
574 575 576
  def getRevocationList(self):
    """
    Get the list of all revoked certificates.
577

Vincent Pelletier's avatar
Vincent Pelletier committed
578 579 580 581 582 583 584 585
    Returns a list of dicts, each containing:
    - revocation_date (int)
      Unix timestamp of certificate revocation.
    - serial (int)
      Revoked certificate's serial.
    """
    with self._db as db:
      c = db.cursor()
586 587 588
      self._execute(
        c,
        'DELETE FROM %(prefix)srevoked WHERE expiration_date < ?',
Vincent Pelletier's avatar
Vincent Pelletier committed
589 590 591 592 593 594 595
        (time(), ),
      )
      return [
        {
          'revocation_date': int(x['revocation_date']),
          'serial': int(x['serial']),
        }
596 597 598
        for x in self._execute(
          c,
          'SELECT revocation_date, serial FROM %(prefix)srevoked',
Vincent Pelletier's avatar
Vincent Pelletier committed
599 600
        )
      ]
601

Vincent Pelletier's avatar
Vincent Pelletier committed
602 603 604 605 606 607
  def dumpIterator(self):
    """
    Backs the *entire* dabase up. This is not limited to tables managed by this
    class (so not limited to table_prefix).
    """
    for statement in self._db.iterdump():
608
      yield toBytes(statement, 'utf-8') + b'\0'
609

Vincent Pelletier's avatar
Vincent Pelletier committed
610 611 612 613 614 615
  @staticmethod
  def restore(db_path, restorator):
    """
    Restores a dump which is the concatenated output of dumpIterator.
    Should not be called directly, but via
    ca.CertificateAuthority.restoreBackup .
616

Vincent Pelletier's avatar
Vincent Pelletier committed
617 618
    db_path (str)
      Path to the SQLite database to produce. Must not exist.
619

620 621 622
    restorator (iterable)
      Produces chunks which correspond (in content, not necessarily in size)
      to what dumpIterator produces.
Vincent Pelletier's avatar
Vincent Pelletier committed
623
    """
624
    buf = b''
Vincent Pelletier's avatar
Vincent Pelletier committed
625 626 627 628
    if os.path.exists(db_path):
      raise ValueError('%r exists, not restoring.' % (db_path, ))
    c = sqlite3.connect(db_path, isolation_level=None).cursor()
    for chunk in restorator:
629
      statement_list = (buf + chunk).split(b'\0')
Vincent Pelletier's avatar
Vincent Pelletier committed
630 631
      buf = statement_list.pop()
      for statement in statement_list:
632
        c.execute(toUnicode(statement, 'utf-8'))
Vincent Pelletier's avatar
Vincent Pelletier committed
633 634
    if buf:
      raise ValueError('Short read, backup truncated ?')