Metadata-Version: 2.5
Name: trytond_certificate_management
Version: 8.0.0.9
Summary: Tryton module certificate_management
Author: Clemens Hupka
Maintainer-email: Clemens Hupka <issues@tryton-erp.eu>
License-Expression: GPL-3.0-or-later
License-File: COPYRIGHT
License-File: LICENSE
Keywords: ca,certificate,certificate_management,tryton,x509
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Environment :: Plugins
Classifier: Framework :: Tryton
Classifier: Topic :: Office/Business
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: trytond-company<8.1,>=8.0
Requires-Dist: trytond-currency<8.1,>=8.0
Requires-Dist: trytond-domains<8.1,>=8.0
Requires-Dist: trytond<8.1,>=8.0
Provides-Extra: test
Description-Content-Type: text/x-rst

Certificate Management
======================

The ``certificate_management`` module provides comprehensive X.509
certificate and certificate authority (CA) management within Tryton.
It consolidates CA management, server/client/public certificate
lifecycles, ACME (Let's Encrypt) integration, certificate revocation,
and CRL generation into a single unified module.

This module supersedes the legacy ``client_cert`` module.  A migration
script (``migration/8.0.0.2.py``) is provided to transfer data from
``client_cert`` into ``certificate_management``.

Dependencies
------------

The module depends on the following Tryton modules:

* ``ir`` — base framework (always required)
* ``res`` — users and groups (always required)
* ``company`` — multi-company support
* ``currency`` — currency handling
* ``domains`` — domain management (used by public certificates for
  ACME issuance)

Installation
------------

Install the module using pip::

    pip install trytond_certificate_management

Or, if running from the monorepo, add the module to your
``PYTHONPATH`` and activate it through the Tryton module
administration interface.

After installation, activate the module in the Tryton client via
*Administration > Modules > Activate / Upgrade*.  The module
registers a top-level **Certificate Management** menu under
*Administration*.

Master Key Configuration
------------------------

Private keys are encrypted at rest with AES-256-GCM under a master key
that is read from the trytond configuration or from the environment and
is **never stored in the database** (issue #689).  A database dump, a
backup or a SQL level read therefore only reveals the ciphertext, not the
key that protects it; only the key *label* is stored on the
``cert.management.configuration`` record.

The options live in the ``[certificate_management]`` section of
``trytond.conf``::

    [certificate_management]
    encryption_key = <256 bit key>
    encryption_key_id = prod-2026-09
    encryption_key_old = <retired key>
    reject_plaintext_keys = true

* ``encryption_key`` (**required**) — the 256 bit master key, either as
  a URL-safe base64 string or as a 64 character hex string.  The hex
  form allows adopting the key material of the legacy ``client_cert``
  module unchanged.  Generate a fresh key with
  ``python -c "from trytond.modules.certificate_management.crypto import
  generate_aes_key; print(generate_aes_key())"``.
* ``encryption_key_id`` (optional) — a free-form label of the key
  (default ``default``), stored on the configuration record for auditing
  and rotation bookkeeping.
* ``encryption_key_old`` (optional) — whitespace or comma separated list
  of retired keys, accepted to *decrypt* values that were not
  re-encrypted yet after a rotation.
* ``reject_plaintext_keys`` (optional) — a stored private key that is
  not ``enc:``-prefixed is refused instead of being served in clear
  text (default ``true``).  See *Plaintext Private Keys* below.

A per-database section ``[certificate_management <database name>]``
takes precedence over the shared one, so a single configuration file can
serve several databases with different keys.  The options can also be
injected through the environment, which is the recommended way to supply
the key from a secrets manager::

    TRYTOND_CERTIFICATE_MANAGEMENT__ENCRYPTION_KEY=<key>
    TRYTOND_CERTIFICATE_MANAGEMENT__ENCRYPTION_KEY_ID=<label>
    TRYTOND_CERTIFICATE_MANAGEMENT__ENCRYPTION_KEY_OLD=<retired key>

The module fails closed: no key is ever generated, no random fallback is
used and no key is ever written back to the database.  Reading or
writing a private key without a valid ``encryption_key`` raises a user
error naming the missing option, rather than storing data that could not
be decrypted again.

.. warning::

   Losing the master key makes every stored private key unreadable;
   since the key is deliberately not part of the database there is no
   recovery path inside Tryton.  Keep it in the same protected place as
   the other deployment secrets and together with the matching database
   backups.

Plaintext Private Keys
~~~~~~~~~~~~~~~~~~~~~~

Every private key written by the module is encrypted with AES-256-GCM
and stored with the ``enc:`` prefix.  A value without that prefix —
written by an import, a manual SQL statement or by a module predating
the encryption at rest — means that the encryption at rest guarantee is
silently degraded, so reading it raises an error by default
(``reject_plaintext_keys``, issue #693) rather than returning the key in
clear text.

The ``migration/8.0.0.8.py`` script is the supported way to fix such
records: it reports every private key stored in clear text in the log
and re-encrypts it with the configured master key, so it is protected at
rest and readable again (see the module docstring of the script for the
exact command).  Setting ``reject_plaintext_keys = false`` restores the
legacy behaviour of returning the value unchanged — with a log entry for
every read — and is only meant as a stopgap while the migration is
prepared.

Key Rotation
~~~~~~~~~~~~

1. Generate a new key, put it in ``encryption_key``, move the previous
   key to ``encryption_key_old`` and set ``encryption_key_id`` to a label
   of the new key.
2. On *Administration > Certificate Management > Configuration*, check
   that ``encryption_key_id`` shows the new label and press
   *Re-encrypt Private Keys* (``reencrypt_keys``).  Every stored private
   key (CA, certificate, Let's Encrypt account, ACME order) is decrypted
   with the new key or one of the retired keys and written back with the
   new key.
3. Drop ``encryption_key_old`` once the rotation completed: no value is
   encrypted with the retired key any more.

Until step 2 succeeds the retired key is needed for every read of an
existing private key, so it must stay configured in the meantime.  The
button raises an error when candidate values exist but none of them
could be decrypted, which usually means the retired key is missing; the
values that could not be decrypted are reported in the log.

Features
--------

CA Management
~~~~~~~~~~~~~

* Create self-signed root CAs and intermediate CAs signed by a parent
  CA.
* CA chain support: retrieve the full chain from root to any CA.
* AES-256-GCM encrypted private key storage at rest, under a master key
  read from the trytond configuration and never stored in the database
  (see `Master Key Configuration`_), with rotation support.
* Single default CA enforcement per system.
* Explicit authorization flag (``issue_client_certs``) deciding which
  CAs may sign client certificates (see issue #688).
* Wizard for guided CA creation with CA:TRUE basic constraints.

Server Certificates
~~~~~~~~~~~~~~~~~~~~

* Subject Alternative Names (DNS and IP).
* Extended Key Usage (serverAuth, server+client auth).
* Optional PKCS#12 bundle for deployment.
* Import via CSR or generate locally.

Client Certificates
~~~~~~~~~~~~~~~~~~~~

* Linked to a Tryton user.
* Signed only by CAs explicitly flagged with ``issue_client_certs``;
  all client-certificate issuance paths validate the signing CA
  server-side (see issue #688).
* PKCS#12 bundles are encrypted with PBES2-AES256-SHA256 (600000 KDF
  rounds).  The deprecated PBES1 3DES/SHA-1 algorithm is off by
  default and, when enabled for import compatibility, may only be
  chosen by certificate administrators with a confirmation; the portal
  HTTP API never accepts it (see issue #692).
* Client cert validity capped at 730 days, and the start date
  (``not_valid_before``) must not be in the past (one-day tolerance
  for clock skew, see issue #690).
* Password-change wizard for client cert PKCS#12 bundles.
* Private-key downloads are password-protected and rate-limited in a
  shared store with lockout escalation (see issue #691).

Public Certificates
~~~~~~~~~~~~~~~~~~~~

* Issued through Let's Encrypt (ACME, RFC 8555).
* Domain references from the ``domains`` module.
* Alternative names (SAN DNS entries) via
  ``cert.management.public_cert_altname``.
* ACME challenge types: DNS-01 and HTTP-01.
* Full certificate chain storage.

ACME Integration
~~~~~~~~~~~~~~~~~

* ``cert.management.le_account`` — ACME account credentials with
  encrypted private key.
* ``cert.management.acme_order`` — full ACME order lifecycle tracking
  (pending → ready → processing → valid/invalid).
* ``cert.management.acme_challenge`` — per-domain challenge state
  (DNS-01 or HTTP-01).

Revocation and CRL
~~~~~~~~~~~~~~~~~~~

* RFC 5280 revocation reason codes (key_compromise, ca_compromise,
  affiliation_changed, cessation_of_operation, superseded,
  certificate_hold).
* ``cert.management.revocation`` audit-trail records.
* ``cert.management.crl`` Certificate Revocation List generation
  signed with the CA private key.
* Automatic CRL regeneration via cron job.
* Unrevoke certificates revoked with ``certificate_hold`` reason.

Scheduled Tasks
~~~~~~~~~~~~~~~

The module registers the following methods in ``ir.cron``:

* ``cert.management.crl|regenerate_all`` — regenerate all active CRLs.
* ``cert.management.certificate|check_expiration`` — check all
  certificates.
* ``cert.management.certificate|check_expiration_server`` — check
  server certificates.
* ``cert.management.certificate|check_expiration_client`` — check
  client certificates.
* ``cert.management.certificate|check_expiration_public`` — check
  public certificates.
* ``cert.management.ca|check_expiration`` — check CA certificates.

Wizards
~~~~~~~~

* **Create CA** — guided self-signed or intermediate CA creation.
* **Create Server Certificate** — generate or import a server
  certificate.
* **Create Client Certificate** — generate a client certificate with
  PKCS#12 bundle.
* **Import CSR** — import an external Certificate Signing Request.
* **Import External Certificate** — import an externally issued
  certificate with key.
* **Renew Certificate** — renew an expiring certificate.
* **Revoke Certificate** — revoke a certificate with a reason code.
* **Download CRL** — download the latest CRL for a CA.
* **Authorise & Issue Public Certificate** — full ACME workflow:
  authorise domain ownership and issue a Let's Encrypt certificate.

Portal Integration
-------------------

The ``flask_board.cfg`` file declares two portal modules for the
flask portal:

* **fe_certificate_management** (frontend) — public-facing module for
  viewing public, server, and client certificates.  Requires login.
  Accessible at ``/certificates``.
* **be_certificate_management** (backend) — admin module for CA
  management, certificate issuance, revocation, CRL, and ACME
  administration.  Requires admin login.  Accessible at
  ``/admin/certificates``.

The ``routes.py`` file exposes the client-certificate wizard and the
private-key downloads over HTTP
(``/cert_management/client_cert/create``,
``/cert_management/client_cert/change_password``,
``/cert_management/client_cert/verify_download_password`` and
``/cert_management/client_cert/download_key``) for portal
self-service, authenticated with ``flask_portal`` user-application
tokens and enforcing user scoping and the 730-day client validity
limit server-side.  See the "HTTP API" section of the documentation.

Record-level access control
---------------------------

``cert.management.certificate`` and
``cert.management.revocation`` are protected by record rules (see
issue #446):

* **Own certificates** (applied to every user by default): a user
  may only read, write, create and revoke certificates (and their
  revocation records) whose ``user`` is the authenticated user.
  Server and public certificates without an owning user are
  therefore visible to administrators only.
* **Any certificate** (assigned to the *Certificate Management
  Administrator* group and the Tryton administrator group): the rule
  group has no rules, so its members see and manage every
  certificate.

The rule domains are evaluated with the current user id exposed as
``user_id`` in the ``ir.rule`` context (see ``ir.py``).  Model
access grants read, write and create on certificates to every user
by default — the record rules provide the scoping — while deletion
stays restricted to the administrator groups.  Reading private key
material (the ``key`` and ``key_encrypted`` fields) remains denied
to non-admin users; only *writing* the generated key of one's own
certificate at creation time is permitted for the self-service
flows.

HTTP routes execute the wizard as the authenticated user with Tryton
access checks enabled, so model access, field access and the record
rules are enforced on every request.

Client-certificate issuance authorization
-----------------------------------------

Signing a certificate decrypts the private key of the selected CA, so
the selection of the signing CA is a security boundary (issue #688):

* ``cert.management.ca`` carries the boolean flag
  ``issue_client_certs`` (default **False**).  A CA may only be used
  as signing CA for client certificates when it is active *and*
  flagged.
* The flag is readable by every user but writable by the *Certificate
  Management Administrator* group and the Tryton administrator group
  only (``ir.model.field.access``).
* Every client-certificate issuance path validates the signing CA
  server-side with ``cert.management.ca.check_client_cert_issuer``:
  the Create Client Certificate wizard (its signing-CA domain lists
  authorized CAs only and defaults to the default authorized CA), the
  CSR import wizard for ``cert_type = client``, the renewal of
  ``clientAuth`` certificates, and the portal HTTP endpoint
  ``POST /cert_management/client_cert/create``, which rejects a
  request naming an unauthorized CA with HTTP 400 before a wizard
  session is created.

.. warning::

   **Upgrade note**: existing CAs are *not* flagged automatically.
   After upgrading this module an administrator must tick *Issue
   Client Certificates* on the CA (or CAs) that are intended to sign
   client certificates — otherwise client-certificate issuance is
   refused with the message that the selected CA is not authorized to
   issue client certificates.  This applies to the portal
   self-service flow as well; the flask portal must offer an
   authorized CA.

.. warning::

   **Direct / co-hosted portal mode limitation**: the flask portal
   ``DataAccess`` backend (``flask_tryton``) runs its transactions
   as the configured ``TRYTON_USER`` (root by default), where Tryton
   access checks are not applied.  Server-side record rules cannot
   enforce per-user scoping in that mode; the portal must apply
   ownership scoping on the frontend side (see flask_portal issue
   #210, merged in MR !118).  Use REST/route mode or a dedicated
   ``TRYTON_USER`` with restricted groups when direct-mode scoping
   is required.

Client-certificate validity window
----------------------------------

A newly issued client certificate must not be backdated (issue #690):
the start date (``not_valid_before``) must not lie in the past, with a
one-day tolerance that absorbs timezone and clock skew between the
application server and the requesting client.  A backdated validity
window would let authentication events appear to fall inside it and
complicate audit and forensics.  Both the Create Client Certificate
wizard and the portal endpoint
``POST /cert_management/client_cert/create`` enforce the rule
server-side (``cert.management.client_cert.check_client_not_before``);
the endpoint rejects such a request with HTTP 400 before a wizard
session is created.

The check is applied at issuance time only: stored, migrated and
imported certificates are not re-validated, so historical validity
dates remain loadable.

Private-key download password verification
------------------------------------------

The portal endpoints
``POST /cert_management/client_cert/verify_download_password`` and
``POST /cert_management/client_cert/download_key`` verify a
caller-supplied password before the private key is served (issue
#447).  The password is checked against the certificate's PKCS12
bundle password.

* **Login-password fallback** — when a certificate has no stored
  PKCS12 bundle (keys imported from an external CSR), the caller's
  Tryton login password is verified instead, but only when the
  ``allow_user_password_fallback`` flag of
  ``cert.management.configuration`` is enabled (issue #691).  The
  flag defaults to **False**: the login password also unlocks the
  full Tryton client, and a dedicated PKCS12 password exists for
  this purpose, so the endpoints must not double as a login-password
  oracle.  Certificates without a bundle therefore reject every
  password until the fallback is enabled explicitly.
* **Shared rate limiter** — failed verifications are counted in the
  ``cert.management.verify.attempt`` table, i.e. in the database
  rather than in a per-process dictionary (issue #691).  The limit
  therefore spans all WSGI workers and application servers and
  survives restarts; the previous implementation undercounted by the
  number of workers and reset on every restart.
* **Per-source window** — at most ``VERIFY_RATE_LIMIT`` (5) failures
  per user and remote address within a sliding window of
  ``VERIFY_RATE_WINDOW`` (60) seconds; further attempts are rejected
  with HTTP 429.
* **Lockout escalation** — once a user accumulates
  ``VERIFY_ESCALATION_THRESHOLD`` (15) failures within
  ``VERIFY_ESCALATION_WINDOW`` (1 hour) across *all* source
  addresses, the account is locked out for ``VERIFY_LOCKOUT_BASE``
  (60) seconds counted from the latest failure; the duration doubles
  on every further multiple of the threshold, capped at
  ``VERIFY_LOCKOUT_MAX`` (1 hour).  A correct password is refused
  while the lockout lasts.  A successful verification clears the
  recorded failures of the caller.
* **Retention** — a cron job
  (``cert.management.verify.attempt|purge_expired``) removes
  attempts older than ``ATTEMPT_RETENTION`` (24 hours), so the table
  only ever holds recent failures.
* The recorded attempts are scoped to their user by a record rule:
  a user can only read, count and delete its own attempts.

All failed verifications are audit-logged server-side.

Legacy PKCS12 encryption
------------------------

New PKCS12 bundles are encrypted with PBES2 AES-256-CBC and a SHA-256
MAC over 600000 KDF rounds (``pbes2_aes256_sha256``).  The deprecated
PBES1 3DES/SHA-1 algorithm (``pbes1_3des_sha1``) is kept for import
compatibility of bundles into legacy systems only and is off by
default (issue #692):

* ``cert.management.configuration.allow_legacy_pkcs12_encryption``
  (default **False**) enables the algorithm for certificate
  administrators.  The flag is readable by every user but writable by
  the *Certificate Management Administrator* group and the Tryton
  administrator group only (``ir.model.field.access``).
* The option is only *offered* to users of those groups and only when
  the flag is set (the selection of the wizard and of
  ``cert.management.certificate.pkcs12_encryption`` is computed per
  user).
* Every use must be confirmed: the wizard raises a ``UserWarning``
  (``res.user.warning`` ``legacy_pkcs12_encryption``) once per user and
  logs the selection.
* The enforcement is layered: the wizard transition, the model
  validation of ``cert.management.certificate`` (so writing the field
  directly does not bypass it) and
  ``crypto.build_pkcs12_bundle`` (which refuses the algorithm unless
  the caller explicitly opts in) all check the permission.
* ``default_pkcs12_encryption`` cannot be set to the deprecated
  algorithm, so no bundle is ever encrypted weakly by accident.
* The portal HTTP API rejects ``pkcs12_encryption =
  "pbes1_3des_sha1"`` with HTTP 400: the endpoints serve regular
  users, who are never certificate administrators.
* Renewing a certificate whose bundle was encrypted with the
  deprecated algorithm falls back to the modern algorithm and logs it,
  as long as the option is disabled.

Migration from ``client_cert`` + ``domains``
--------------------------------------------

The migration script ``migration/8.0.0.2.py`` migrates data from the
legacy ``client_cert`` module into ``certificate_management``:

=====================================  =========================================
Legacy table                           Target model
=====================================  =========================================
``clientcert_ca``                      ``cert.management.ca``
``clientcert_servercert``              ``cert.management.certificate``
                                       (``extended_key_usage=serverAuth``)
``clientcert_clientcert``              ``cert.management.certificate``
                                       (``extended_key_usage=clientAuth``)
``clientcert_configuration``           ``cert.management.configuration``
=====================================  =========================================

Private keys are re-encrypted during migration: legacy raw
``nonce || ciphertext`` values encrypted with the hex key from
``clientcert_configuration`` are converted to ``enc:``-prefixed
urlsafe-base64 values encrypted with the master key of the
``[certificate_management]`` section (see `Master Key Configuration`_),
which therefore has to be configured *before* the migration runs.  Keys
that cannot be decrypted with the legacy key are migrated without their
private key and reported in the log.

Upgrading from a database-stored master key
-------------------------------------------

Up to 8.0.0.5 the master key was stored in the database
(``cert_management_configuration.encryption_key``) and auto-generated on
first access.  ``migration/8.0.0.5.py`` moves it out of the database
(issue #689):

1. Stop the Tryton server, then read the key currently stored in the
   database with
   ``SELECT encryption_key FROM cert_management_configuration;``.
2. Adopting it is the safest option: put it in ``trytond.conf`` together
   with a label, so no private key has to be re-encrypted::

       [certificate_management]
       encryption_key = <the key read from the database>
       encryption_key_id = <label, e.g. prod-2026-09>

   Alternatively set ``encryption_key`` to a *new* key to rotate at the
   same time: the values encrypted with the legacy key are decrypted
   with it and written back with the new key, so nothing is lost.
3. Update the module with
   ``trytond-admin -c <config> -d <database> -u certificate_management``.
4. Run the migration script through ``Pool`` (the exact snippet is in the
   docstring of ``migration/8.0.0.5.py``); it re-encrypts every stored
   private key with the configured master key, writes the key label to
   the configuration record and finally drops the legacy column.

The script is idempotent and resumable: it exits without changes when the
legacy column is gone, skips values already re-encrypted by an
interrupted run, and keeps the legacy column when a value cannot be
decrypted, so the configuration can be fixed and the script repeated.
