Skip to content

Commit f946143

Browse files
authored
Merge pull request #352 from SUNET/feat/keys
feat!:Support EC, Ed25519, RSA-PSS and post-quantum signing keys
2 parents 3180ea6 + b2c74ba commit f946143

11 files changed

Lines changed: 1187 additions & 15 deletions

File tree

‎.github/workflows/python-package.yml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,16 @@ jobs:
3737
uv sync --locked --all-extras --dev
3838
3939
40+
- name: Install SoftHSM2 and OpenSC for PKCS#11 signing tests
41+
run: |
42+
sudo apt-get update
43+
sudo apt-get install -y softhsm2 opensc
44+
4045
- name: Run tests
46+
env:
47+
# Fail instead of skipping the SoftHSM2 signing tests if the token
48+
# cannot be set up or a key type cannot be generated.
49+
PYFF_REQUIRE_SOFTHSM: "1"
4150
run: |
4251
uv run python -m coverage erase
4352
uv run python -m coverage run -m pytest --cov=src/pyff

‎docs/usage/examples.rst‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,3 +256,58 @@ you are using a unix-like environment).
256256
.. code-block:: bash
257257
258258
# env PYKCS11PIN=secret1 SOFTHSM_CONF=softhsm.conf pyff --loglevel=DEBUG p11.fd
259+
260+
Example 5 - Sign with EC, Ed25519 or post-quantum keys
261+
------------------------------------------------------
262+
263+
The ``sign`` pipe accepts any key type pybergshamra can load, not only RSA. The XML-DSig
264+
``SignatureMethod`` is chosen from the type of the key:
265+
266+
================ ===============================================================
267+
Key type Default signature_method
268+
================ ===============================================================
269+
RSA ``rsa-sha256``
270+
EC P-256 ``ecdsa-sha256``
271+
EC P-384 ``ecdsa-sha384``
272+
EC P-521 ``ecdsa-sha512``
273+
Ed25519 ``eddsa-ed25519``
274+
ML-DSA-44/65/87 ``ml-dsa-44`` / ``ml-dsa-65`` / ``ml-dsa-87`` (W3C URI)
275+
SLH-DSA-SHA2-* ``slh-dsa-sha2-128s`` ... ``slh-dsa-sha2-256f`` (W3C URI)
276+
================ ===============================================================
277+
278+
.. code-block:: yaml
279+
280+
- sign:
281+
key: ec-signer.key
282+
cert: ec-signer.crt
283+
284+
Use ``signature_method`` to choose another method for the same key type, e.g. ``rsa-pss-sha256`` for an RSA
285+
key, ``ecdsa-sha384`` for a P-256 key, or ``ml-dsa-65-xmlsec`` to emit the libxmlsec1 URI for ML-DSA instead of
286+
the W3C one. A full algorithm URI is accepted too. ``digest_method`` selects the Reference digest (``sha256`` by
287+
default; ``sha384``, ``sha512``, ``sha3-256``, ``sha3-384``, ``sha3-512``).
288+
289+
.. code-block:: yaml
290+
291+
- sign:
292+
key: rsa-signer.key
293+
cert: rsa-signer.crt
294+
signature_method: rsa-pss-sha256
295+
digest_method: sha256
296+
297+
For a PKCS#11 key the key type is read from ``cert``; without a ``cert`` (and without ``signature_method``) pyFF
298+
signs with ``rsa-sha256`` as before. ECDSA on a token needs the curve, taken from ``cert`` or from ``ec_curve``
299+
(``P-256``, ``P-384`` or ``P-521``). Tokens support RSA, RSA-PSS, ECDSA and Ed25519 keys; ML-DSA and SLH-DSA
300+
need an on-disk key.
301+
302+
.. code-block:: yaml
303+
304+
- sign:
305+
key: pkcs11:///usr/lib/softhsm/libsofthsm2.so/ec-signer
306+
token_label: mdsigner
307+
signature_method: ecdsa-sha256
308+
ec_curve: P-256
309+
310+
Before switching the signing key type, check that every metadata consumer can verify the new algorithm: ECDSA is
311+
widely supported, while Ed25519, ML-DSA and SLH-DSA are not yet. The ``certreport`` pipe checks EC keys against
312+
``ec_error_bits`` (default 224) and ``ec_warning_bits`` (default 256) rather than the RSA ``error_bits`` /
313+
``warning_bits`` limits.

‎src/pyff/builtins.py‎

Lines changed: 177 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from pyuppsala.etree import DocumentInvalid
2525
from str2bool import str2bool
2626

27+
from pyff import sigalg
2728
from pyff.constants import NS, config
2829
from pyff.decorators import deprecated
2930
from pyff.exceptions import MetadataException
@@ -1269,7 +1270,19 @@ def _select_pkcs11_provider(
12691270
return provider
12701271

12711272

1272-
def _sign_pkcs11(provider, module_path, pin, label, xml, *, reference_id=None, cert_pem=None):
1273+
def _sign_pkcs11(
1274+
provider,
1275+
module_path,
1276+
pin,
1277+
label,
1278+
xml,
1279+
*,
1280+
reference_id=None,
1281+
cert_pem=None,
1282+
signature_method=pybergshamra.Algorithm.RSA_SHA256,
1283+
digest_method=sigalg.DEFAULT_DIGEST_METHOD,
1284+
ec_curve=None,
1285+
):
12731286
"""Serialize token logins and release authenticated objects even on errors."""
12741287
# Different selectors can resolve to the same token. Lock its actual slot,
12751288
# rather than the configured label/serial/slot selector or key label.
@@ -1281,10 +1294,17 @@ def _sign_pkcs11(provider, module_path, pin, label, xml, *, reference_id=None, c
12811294
session = signer = ctx = None
12821295
try:
12831296
session = provider.open_session(pin)
1284-
signer = pybergshamra.Pkcs11Signer(session, label, pybergshamra.Algorithm.RSA_SHA256)
1297+
signer = pybergshamra.Pkcs11Signer(session, label, signature_method, ec_curve=ec_curve)
12851298
ctx = pybergshamra.DsigContext(pybergshamra.KeysManager())
12861299
ctx.set_hsm_signer(signer)
1287-
return pybergshamra.sign_enveloped(ctx, xml, reference_id=reference_id, cert_pem=cert_pem)
1300+
return pybergshamra.sign_enveloped(
1301+
ctx,
1302+
xml,
1303+
reference_id=reference_id,
1304+
cert_pem=cert_pem,
1305+
signature_method=signature_method,
1306+
digest_method=digest_method,
1307+
)
12881308
finally:
12891309
# Exception tracebacks retain Python frames. Clear every local
12901310
# owner before unlocking so a failed request cannot retain login.
@@ -1293,6 +1313,54 @@ def _sign_pkcs11(provider, module_path, pin, label, xml, *, reference_id=None, c
12931313
session = None
12941314

12951315

1316+
def _pkcs11_signature_method(method_override, cert_pem, ec_curve) -> tuple[str, Optional[str]]:
1317+
"""Pick the signature method and EC curve for a PKCS#11 key.
1318+
1319+
The token key cannot be inspected, so its type comes from the signing
1320+
certificate when one is configured. Precedence for the method is
1321+
``signature_method`` > certificate key type > rsa-sha256; for the curve it
1322+
is ``ec_curve`` > certificate curve.
1323+
"""
1324+
cert_key_type = None
1325+
if cert_pem is not None:
1326+
try:
1327+
cert_key_type = pybergshamra.load_x509_cert_pem(cert_pem.encode()).algorithm_name
1328+
except pybergshamra.BergshamraError as ex:
1329+
raise PipeException(f"Unable to read the signing certificate: {ex}") from ex
1330+
1331+
if method_override is not None:
1332+
signature_method = method_override
1333+
if cert_key_type is not None:
1334+
sigalg.check_compatible(signature_method, cert_key_type)
1335+
elif cert_key_type is not None:
1336+
signature_method = sigalg.default_signature_method(cert_key_type)
1337+
else:
1338+
signature_method = pybergshamra.Algorithm.RSA_SHA256
1339+
1340+
if not sigalg.pkcs11_supported(signature_method):
1341+
raise PipeException(
1342+
f"signature_method {signature_method} is not supported by the PKCS#11 signer; "
1343+
"use RSA, RSA-PSS, ECDSA or Ed25519 keys on a token"
1344+
)
1345+
1346+
if sigalg.method_family(signature_method) != "ecdsa":
1347+
return signature_method, None
1348+
1349+
if ec_curve is None and cert_key_type is not None:
1350+
ec_curve = sigalg.ec_curve_for(cert_key_type)
1351+
if ec_curve is None:
1352+
raise PipeException(
1353+
"ECDSA signing with a PKCS#11 key needs a cert or the ec_curve argument (P-256, P-384, P-521)"
1354+
)
1355+
ec_curve = str(ec_curve).strip().upper()
1356+
if ec_curve not in ("P-256", "P-384", "P-521"):
1357+
raise PipeException(f"Unsupported ec_curve {ec_curve!r}; use P-256, P-384 or P-521")
1358+
cert_curve = sigalg.ec_curve_for(cert_key_type) if cert_key_type is not None else None
1359+
if cert_curve is not None and cert_curve != ec_curve:
1360+
raise PipeException(f"ec_curve {ec_curve} does not match the {cert_key_type} signing certificate")
1361+
return signature_method, ec_curve
1362+
1363+
12961364
@pipe
12971365
def sign(req: Plumbing.Request, *_opts):
12981366
"""
@@ -1304,9 +1372,36 @@ def sign(req: Plumbing.Request, *_opts):
13041372
:return: returns the signed working document
13051373
13061374
Sign expects a single dict with at least a 'key' key and optionally a 'cert' key. The 'key' argument references
1307-
either a PKCS#11 uri or the filename containing a PEM-encoded non-password protected private RSA key.
1308-
The 'cert' argument may be empty in which case the cert is looked up using the PKCS#11 token, or may point
1309-
to a file containing a PEM-encoded X.509 certificate.
1375+
either a PKCS#11 uri or the filename containing a non-password protected private key (RSA, EC P-256/P-384/P-521,
1376+
Ed25519, ML-DSA or SLH-DSA; PEM or DER). The 'cert' argument may be empty in which case the cert is looked up
1377+
using the PKCS#11 token, or may point to a file containing a PEM-encoded X.509 certificate.
1378+
1379+
**Key types and algorithms**
1380+
1381+
The XML-DSig SignatureMethod is chosen from the type of the signing key:
1382+
1383+
================ ===============================================================
1384+
Key type Default signature_method
1385+
================ ===============================================================
1386+
RSA ``rsa-sha256``
1387+
EC P-256 ``ecdsa-sha256``
1388+
EC P-384 ``ecdsa-sha384``
1389+
EC P-521 ``ecdsa-sha512``
1390+
Ed25519 ``eddsa-ed25519``
1391+
ML-DSA-44/65/87 ``ml-dsa-44`` / ``ml-dsa-65`` / ``ml-dsa-87`` (W3C URI)
1392+
SLH-DSA-SHA2-* ``slh-dsa-sha2-128s`` ... ``slh-dsa-sha2-256f`` (W3C URI)
1393+
================ ===============================================================
1394+
1395+
Set ``signature_method`` to override it, either with one of the short names above, ``rsa-sha384``,
1396+
``rsa-sha512``, ``rsa-pss-sha256``, ``rsa-pss-sha384``, ``rsa-pss-sha512``, the libxmlsec1 URIs of the
1397+
post-quantum algorithms (``ml-dsa-65-xmlsec``, ``slh-dsa-sha2-128s-xmlsec``, ...), or a full algorithm URI.
1398+
The method must match the key type. ``digest_method`` (default ``sha256``; also ``sha384``, ``sha512``,
1399+
``sha3-256``, ``sha3-384``, ``sha3-512`` or a URI) selects the Reference digest.
1400+
1401+
For a PKCS#11 key pyFF cannot inspect the private key, so the key type is taken from the 'cert'. Without a
1402+
'cert' (and without ``signature_method``) ``rsa-sha256`` is used. ECDSA on a token also needs the curve,
1403+
which comes from the 'cert' or from ``ec_curve`` (``P-256``, ``P-384`` or ``P-521``). PKCS#11 keys support
1404+
RSA, RSA-PSS, ECDSA and Ed25519; ML-DSA and SLH-DSA require an on-disk key.
13101405
13111406
When several initialized tokens are visible, select one with ``token_label`` and optional ``token_serial``,
13121407
or with ``slot_id``. Token selection requires pybergshamra 0.8.1 or newer. The slot may alternatively be
@@ -1347,6 +1442,16 @@ def sign(req: Plumbing.Request, *_opts):
13471442
13481443
This example signs the document using the plain key and cert found in the signer.key and signer.crt files.
13491444
1445+
.. code-block:: yaml
1446+
1447+
- sign:
1448+
key: pkcs11:///usr/lib/softhsm/libsofthsm2.so/ec-signer
1449+
token_label: mdsigner
1450+
cert: /etc/credentials/ec-signer.crt
1451+
signature_method: ecdsa-sha384 # optional; ecdsa-sha256 for a P-256 cert by default
1452+
1453+
This signs with an EC key on a token; the curve is read from the certificate.
1454+
13501455
"""
13511456
if req.t is None:
13521457
raise PipeException("Your pipeline is missing a select statement.")
@@ -1365,6 +1470,16 @@ def sign(req: Plumbing.Request, *_opts):
13651470
if cert_file is None:
13661471
log.info("Attempting to extract certificate from token...")
13671472

1473+
# Resolve the algorithm overrides up front so a typo fails before any key
1474+
# is loaded or any token login happens.
1475+
method_override = req.args.get('signature_method')
1476+
if method_override is not None:
1477+
method_override = sigalg.resolve_signature_method(method_override)
1478+
digest_method = req.args.get('digest_method')
1479+
digest_method = (
1480+
sigalg.DEFAULT_DIGEST_METHOD if digest_method is None else sigalg.resolve_digest_method(digest_method)
1481+
)
1482+
13681483
# Build the signing context. The reference id (if any) comes from the @ID
13691484
# attribute on the document root; pybergshamra already treats "ID" as a
13701485
# default id attribute, so we must NOT call ctx.add_id_attr("ID").
@@ -1391,6 +1506,7 @@ def sign(req: Plumbing.Request, *_opts):
13911506
else:
13921507
pin = pin_spec
13931508

1509+
signature_method, ec_curve = _pkcs11_signature_method(method_override, cert_pem, req.args.get('ec_curve'))
13941510
provider = _select_pkcs11_provider(
13951511
module_path,
13961512
uri_slot_id=uri_slot_id,
@@ -1401,7 +1517,18 @@ def sign(req: Plumbing.Request, *_opts):
14011517
# Keep HSM signing on an owned XML string. Authentication and all
14021518
# operation objects must be released before the next token login.
14031519
xml = etree.tostring(relt, encoding='unicode')
1404-
signed = _sign_pkcs11(provider, module_path, pin, label, xml, reference_id=idattr, cert_pem=cert_pem)
1520+
signed = _sign_pkcs11(
1521+
provider,
1522+
module_path,
1523+
pin,
1524+
label,
1525+
xml,
1526+
reference_id=idattr,
1527+
cert_pem=cert_pem,
1528+
signature_method=signature_method,
1529+
digest_method=digest_method,
1530+
ec_curve=ec_curve,
1531+
)
14051532
req.t = root(etree.fromstring(signed))
14061533
return req.t
14071534
else:
@@ -1410,6 +1537,12 @@ def sign(req: Plumbing.Request, *_opts):
14101537
ctx = pybergshamra.DsigContext(mgr)
14111538
key = pybergshamra.load_key_file(key_file)
14121539
mgr.add_key(key)
1540+
if method_override is None:
1541+
signature_method = sigalg.default_signature_method(key.algorithm_name)
1542+
else:
1543+
sigalg.check_compatible(method_override, key.algorithm_name)
1544+
signature_method = method_override
1545+
log.debug(f"signing with a {key.algorithm_name} key using {signature_method}")
14131546

14141547
if is_document_root(relt):
14151548
# The document API uses an owned XML handoff and imports the signed
@@ -1422,15 +1555,29 @@ def sign(req: Plumbing.Request, *_opts):
14221555
# would land on the discarded EntitiesDescriptor, leaving the emitted
14231556
# entity unsigned.
14241557
doc = etree.native_document(relt)
1425-
pybergshamra.sign_enveloped_document(ctx, doc, reference_id=idattr, cert_pem=cert_pem)
1558+
pybergshamra.sign_enveloped_document(
1559+
ctx,
1560+
doc,
1561+
reference_id=idattr,
1562+
cert_pem=cert_pem,
1563+
signature_method=signature_method,
1564+
digest_method=digest_method,
1565+
)
14261566
req.t = relt
14271567
else:
14281568
# A subtree of a larger document (small, so the
14291569
# string round trip is cheap): serialize the working document, build
14301570
# the enveloped signature, sign, and reparse so downstream pipes see a
14311571
# standalone pyuppsala element.
14321572
xml = etree.tostring(relt, encoding='unicode')
1433-
signed = pybergshamra.sign_enveloped(ctx, xml, reference_id=idattr, cert_pem=cert_pem)
1573+
signed = pybergshamra.sign_enveloped(
1574+
ctx,
1575+
xml,
1576+
reference_id=idattr,
1577+
cert_pem=cert_pem,
1578+
signature_method=signature_method,
1579+
digest_method=digest_method,
1580+
)
14341581
req.t = root(etree.fromstring(signed))
14351582

14361583
return req.t
@@ -1750,11 +1897,17 @@ def certreport(req: Plumbing.Request, *opts):
17501897
warning_seconds: 864000
17511898
error_bits: 1024
17521899
warning_bits: 2048
1900+
ec_error_bits: 224
1901+
ec_warning_bits: 256
17531902
17541903
For key size checking this will report keys with a size *less* than the size specified, defaulting to errors
17551904
for keys smaller than 1024 bits and warnings for keys smaller than 2048 bits. It should be understood as the
17561905
minimum key size for each report level, as such everything below will create report entries.
17571906
1907+
``error_bits`` and ``warning_bits`` apply to RSA and DSA keys. EC keys are checked against ``ec_error_bits``
1908+
(default 224) and ``ec_warning_bits`` (default 256) instead. Ed25519, Ed448, ML-DSA and SLH-DSA keys have a
1909+
fixed strength and are not checked for size; their expiry is still reported.
1910+
17581911
Remember that you need a 'publish' or 'emit' call after certreport in your plumbing to get useful output. PyFF
17591912
ships with a couple of xslt transforms that are useful for turning metadata with certreport annotation into
17601913
HTML.
@@ -1774,6 +1927,8 @@ def certreport(req: Plumbing.Request, *opts):
17741927
warning_seconds = int(req.args.get('warning_seconds', "864000"))
17751928
error_bits = int(req.args.get('error_bits', "1024"))
17761929
warning_bits = int(req.args.get('warning_bits', "2048"))
1930+
ec_error_bits = int(req.args.get('ec_error_bits', "224"))
1931+
ec_warning_bits = int(req.args.get('ec_warning_bits', "256"))
17771932

17781933
# One native pass: iterate entities directly and walk each (small) entity
17791934
# subtree for its certificates. The previous per-entity document-wide
@@ -1800,20 +1955,29 @@ def certreport(req: Plumbing.Request, *opts):
18001955
cert = cert_info(cert_pem)
18011956
subject = cert.subject
18021957
keysize = cert.keysize
1803-
if keysize is not None and keysize < error_bits:
1958+
# Size limits depend on the key family: RSA/DSA bits are not
1959+
# comparable to EC bits, and EdDSA / ML-DSA / SLH-DSA have
1960+
# fixed strengths, so they are never flagged.
1961+
key_family = cert.key_family
1962+
min_error, min_warning = error_bits, warning_bits
1963+
if key_family == "ec":
1964+
min_error, min_warning = ec_error_bits, ec_warning_bits
1965+
elif key_family not in ("rsa", "dsa"):
1966+
keysize = None
1967+
if keysize is not None and keysize < min_error:
18041968
annotate_entity(
18051969
entity_elt,
18061970
"certificate-error",
18071971
"keysize too small",
1808-
f"{subject} has keysize of {keysize} bits (less than {error_bits})",
1972+
f"{subject} has keysize of {keysize} bits (less than {min_error})",
18091973
)
18101974
log.error(f"{eid} has keysize of {keysize}")
1811-
elif keysize is not None and keysize < warning_bits:
1975+
elif keysize is not None and keysize < min_warning:
18121976
annotate_entity(
18131977
entity_elt,
18141978
"certificate-warning",
18151979
"keysize small",
1816-
f"{subject} has keysize of {keysize} bits (less than {warning_bits})",
1980+
f"{subject} has keysize of {keysize} bits (less than {min_warning})",
18171981
)
18181982
log.warning(f"{eid} has keysize of {keysize}")
18191983

0 commit comments

Comments
 (0)