Metadata-Version: 2.5
Name: trytond_certificate_management
Version: 8.0.0.20
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-keycloak-auth<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)
* ``keycloak_auth`` — Keycloak/OIDC bearer authentication of the HTTP
  API (issue #783): the calling ``res.user`` is resolved by exact
  ``login`` and the routes run with the access checks of that user.

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 accepts it only when the instance additionally enables it
  for the portal, because some importers (Android 12/13) require it
  (see issues #692 and #836).
* 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).
* PKCS#12 bundles are named after their own filename pattern
  (``pkcs12_filename_pattern``, default
  ``client_cert_{common_name}.p12``) and always carry a ``.p12`` (or
  ``.pfx``) extension: the binary bundle is never served under the
  ``.pem`` extension of the PEM certificate pattern, which broke the
  importers that filter by extension (see issue #826).
* 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
~~~~~~~~~~~~~~~~~~~

* Revocation reason codes: the RFC 5280 codes (key_compromise,
  ca_compromise, affiliation_changed, cessation_of_operation,
  superseded, certificate_hold) plus ``password_lost`` for a lost
  PKCS#12 password, which the generated CRL carries as ``superseded``
  because RFC 5280 has no code of its own for it (issue #833).
* ``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.

The three create wizards apply the `Certificate subject defaults`_ of
the configuration to the certificates they issue.

The five record-independent wizards (**Create CA**, **Create Server
Certificate**, **Create Client Certificate**, **Import CSR** and
**Import External Certificate**) create the record they operate on and
need no existing one, so each of them is also registered under the
**New** submenu of the *Certificate Management* menu.  They stay
available from the *Launch action* dropdown of the CA and certificate
toolbars as well, but that dropdown is only sensitive while a saved
record is selected; on an instance that does not hold a CA yet the
menu entry is therefore the only way to launch *Create CA* and produce
the first record (issue #846).  The wizards operating on a selected
record (**Renew Certificate**, **Revoke Certificate**, **Download
CRL**, **Authorise & Issue Public Certificate**) are offered by the
*Launch action* dropdown only, which is where their record is selected.

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 certificate detail page of the frontend module offers only the
actions listed in the ``CERT_DETAIL_ACTIONS`` configuration parameter,
which ``flask_board.cfg`` declares with the default ``p12,revoke`` (the
installable PKCS#12 bundle and the *Revoke* button).  The parameter is a
comma-separated list of action ids out of ``pem``, ``der``, ``chain``,
``key``, ``p12``, ``renew`` and ``revoke``; an action that is listed is
still only rendered when it is actually available (``key`` is never
offered in route mode, ``revoke`` only for a valid or expiring
certificate, ``renew`` only for an expiring or expired one), and an
unset or unknown value falls back to the default without an error
(issue #834).

The ``routes.py`` file exposes the client-certificate wizard and the
password-verified private-key and PKCS#12 downloads over HTTP
(``/cert_management/client_cert/create``,
``/cert_management/client_cert/change_password``,
``/cert_management/client_cert/verify_download_password``,
``/cert_management/client_cert/download_key`` and
``/cert_management/client_cert/download_pkcs12``) for portal
self-service, authenticated with the user's Keycloak/OIDC access token
(``keycloak_auth``, issue #783): the token is validated server-side,
the caller is resolved to an active ``res.user`` by exact ``login``
and the route runs as that user, so user scoping and the 730-day
client validity limit are enforced server-side.  The
``res.user.application`` tokens the endpoints accepted before
(tryton-env-mono#802) are no longer honoured.  See the "HTTP API"
section of the documentation.

It also exposes the read surface the portal needs to list the
certificates of the caller, a single certificate and the certificate
authorities (issue #819), which the ``flask_board.cfg`` route map of
the frontend module expects: ``GET /cert_management/certificates``
(a search with ``domain``, ``fields``, ``offset``, ``limit`` and
``order``, answered as the paginated
``records``/``total``/``offset``/``limit``/``next`` shape),
``GET /cert_management/certificates/<id>`` (a single certificate, or
``404`` when it is not readable for the caller),
``GET /cert_management/cas`` and ``GET /cert_management/crls``.  Every
read endpoint authenticates like the wizard routes and runs as the
resolved user with the access checks enabled, so the record rules
scope the answer to the caller; the ``domain`` of a request only
narrows it.  A requested field the model does not have is answered as
``null``, and the fields carrying key material (``key``,
``key_encrypted``, ``pkcs12_bundle``) are never serialized.

A revoked certificate is *archived* by ``Certificate.revoke()``
(``active`` becomes ``False``), so it is invisible to every search that
does not name ``active``.  The single read and the downloads resolve
such a record all the same (issue #838), so a portal can render the
detail page of a certificate it revoked — its ``revoked``,
``revocation_date`` and ``revocation_reason`` fields and the computed
``status`` are readable through ``fields`` — and download what was
revoked (the PEM, the DER and the chain are public material).  The
lookup stays scoped to the caller by the same record rules, so a
foreign certificate is still a ``404``, and the ``403`` the private-key
and PKCS12 routes answer for a revoked certificate is unchanged.

It additionally exposes the downloads the FE download view performs
(issue #820), which the ``cch_client_cert`` to
``certificate_management`` migration had dropped (an unmatched
``GET`` was answered ``405``): ``GET
/cert_management/certificates/<id>/download`` (the certificate itself,
``format=pem`` by default under ``application/x-pem-file`` or
``format=der`` under ``application/pkix-cert``) and ``GET
/cert_management/certificates/<id>/download_chain`` (the leaf followed
by its signing CA up to the root, as PEM).  Both are scoped to the
caller by the same record rules, so a foreign certificate is a
``404``.  The private key is deliberately *not* served by a
bearer-only download: it stays behind the password-verified ``POST
/cert_management/client_cert/download_key`` (issue #447), so key
material is never handed out on the strength of the access token
alone.  The PKCS12 bundle is served by the password-verified ``POST
/cert_management/client_cert/download_pkcs12`` (issue #831), the same
gate, so the portal can offer the ``.p12`` of an already-issued
certificate; the create endpoint also returns it, base64-encoded, for
freshly issued ones.

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.

Company scoping
---------------

``cert.management.ca``, ``cert.management.certificate`` and
``cert.management.revocation`` carry a ``company`` field, and the
company rule groups of issue #699 confine the CAs, the certificates
and their revocations to the companies of the session (issue #818
revised how they are enforced):

* the company rule groups are *global*, so the company scoping is
  AND-ed with the ownership rules above: a user reaches neither the
  records of another company nor the certificates of another user of
  their own company.  A record whose ``company`` is empty is shared
  and stays visible in every company;
* the members of the *Certificate Management Administrator* group and
  of the Tryton administrator group are **exempt** from the company
  rules (issue #818): an administrator whose session company differs
  from the company of a record can still manage it, which is what the
  lock-out reported in issue #818 prevented;
* to manage a record of another company, either hold one of those two
  groups or switch the session company (*Current Company* / *Company
  Filter* of the user preferences) to one of the record.

The exemption is read from the ``company_rule_bypass`` entry the
``ir.rule`` extension exposes (see ``ir.py``); it is deliberately not
built from a ``default_p`` rule group with an empty bypass group, as
that would move the company scoping into the OR-ed part of the rule
evaluation (``ir.rule.Rule.get``) and hand every certificate of the
company of a user to that user, voiding the ownership rules.

.. warning::

   **Rule groups without module data**: the rule groups of the module
   are defined by ``access_rights.xml`` and are re-applied by every
   module update.  A rule group of one of the models above that no
   module data file defines was created outside of a module revision —
   by an intermediate build deployed on the database, by a database
   script or by hand in the client — so no update corrects or removes
   it.  A *global* one with restrictive rules refuses every user of its
   model, which is the lock-out reported in issue #818: the group named
   *The user is member of the company* of the reported instance is
   defined by no revision of this module.  The
   ``ir.rule.group|check_orphan_rule_groups`` method (see ``ir.py``,
   also usable as a scheduled *ir.cron* job) reports such groups;
   review them and delete the unexpected ones in the client.  Do not
   delete them with raw SQL: the evaluated rule domains are cached per
   process and user, and only the ORM clears that cache.

   The rule groups of a database are listed with::

       SELECT g.id, g.name, g."model", g.global_p, g.default_p, d.module
       FROM ir_rule_group g
       LEFT JOIN ir_model_data d
           ON d.model = 'ir.rule.group' AND d.db_id = g.id
       WHERE g."model" LIKE 'cert.management.%'
       ORDER BY g.id;

   The rows without a ``module`` are the groups no module data file
   defines.

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 interactive use is confirmed: the wizard raises a
  ``UserWarning`` (``res.user.warning``
  ``legacy_pkcs12_encryption``) once per user and logs the selection.
  A portal request is not an interactive use (the endpoint can not
  answer a confirmation dialog), so it is only logged.
* 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 by default: 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.

The deprecated algorithm builds a *real* PBES1 bundle (3DES with a
SHA-1 MAC, 2048 KDF rounds) and not the best-available algorithm of the
installed OpenSSL: on OpenSSL 3 the latter is PBES2 AES-256-CBC with a
SHA-256 MAC, i.e. the modern family under a legacy label, and the
importers this algorithm exists for reject such a bundle with *wrong
password* (Android 12/13, see issue #836).

Legacy PKCS12 bundles for the portal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Some importers accept only the deprecated PBES1 3DES/SHA-1 form, so an
instance may explicitly open the algorithm to the portal endpoints,
which serve regular users that are never certificate administrators
(issue #836):

* ``cert.management.configuration.allow_legacy_pkcs12_for_portal``
  (default **False**) allows the portal-driven creation and
  re-download of deprecated bundles.  Like the flag above it is
  readable by every user but writable by the *Certificate Management
  Administrator* group and the Tryton administrator group only.
* The base ``allow_legacy_pkcs12_encryption`` flag stays a
  prerequisite: the portal opt-in never opens the algorithm on an
  instance that did not already allow it.
* The opt-in bypasses the certificate-administrator *group* check for
  the portal requests only, which means that any writer may then select
  the deprecated algorithm on a certificate it may write.  The creation
  wizard keeps the administrator-only selection, so a regular user is
  never invited to produce a weak bundle by hand, while the
  ``pkcs12_encryption`` field of the certificate itself offers the
  value because it is the field the portal endpoint writes.
* ``POST .../client_cert/create`` and
  ``POST .../client_cert/change_password`` accept
  ``pkcs12_encryption = "pbes1_3des_sha1"`` once the opt-in is set, and
  the permission is always resolved server-side (the request body can
  never widen it).
* ``POST .../client_cert/download_pkcs12`` accepts the same
  ``pkcs12_encryption`` field and re-encrypts the stored bundle to the
  requested algorithm with the password it just verified, so an
  already-issued certificate can be re-downloaded in an importable
  form.  The rebuilt bundle is served, never written back, and the
  bundle of a revoked certificate is refused as before.
* ``flask_board.cfg`` of the frontend portal module declares
  ``config_CERT_PKCS12_ENCRYPTION =
  pbes2_aes256_sha256|pbes1_3des_sha1``: the pipe-separated selection
  the portal offers to the user, the first entry being the default.

Certificate subject defaults
----------------------------

The X.509 subject attributes of a certificate created by the **Create
CA**, **Create Server Certificate** and **Create Client Certificate**
wizards default to the values of the *Certificate Management
configuration*: an instance sets ``default_country``,
``default_state_or_province_name``, ``default_locality_name``,
``default_organization_name``, ``default_organizational_unit`` and
``default_email_address`` once, and every issued certificate carries
them (issue #827):

* The start view of the wizard offers the configured values, so they
  are visible before the certificate is created and can be overridden
  per certificate.
* A subject attribute left empty falls back to the attribute of the
  signing CA — the parent CA of an intermediate CA.
* The e-mail address of an authority is never copied: it identifies
  the operator of the CA and not the subject of the certificate it
  signs, so only ``default_email_address`` provides it.
* The country is uppercased and truncated to the two character
  ISO 3166-1 alpha-2 rule of the X.509 country attribute, so a
  configured value such as ``deu`` is stored as ``DE``.

The attributes are resolved when the certificate is created, in the
transition of the wizard, so every issuance path applies them: the
desktop client, the portal self-service flow and the HTTP endpoint
``POST /cert_management/client_cert/create`` (see `Portal
Integration`_), which send only the fields they know.

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.
