Skip to content

Commit

Permalink
chore: formatting and mypy fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
renatav committed Nov 30, 2024
1 parent 789b591 commit 385a0be
Show file tree
Hide file tree
Showing 6 changed files with 24 additions and 75 deletions.
27 changes: 0 additions & 27 deletions taf/api/utils/_roles.py

This file was deleted.

3 changes: 1 addition & 2 deletions taf/api/yubikey.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

from pathlib import Path
from logdecorator import log_on_end, log_on_error, log_on_start
from taf.api.utils._roles import get_roles_and_paths_of_key
from taf.auth_repo import AuthenticationRepository
from taf.constants import DEFAULT_RSA_SIGNATURE_SCHEME
from taf.exceptions import TAFError
Expand Down Expand Up @@ -41,7 +40,7 @@ def export_yk_public_pem(path: Optional[str] = None) -> None:
"""
try:
pub_key_pem = yk.export_piv_pub_key().decode("utf-8")
except Exception as e:
except Exception:
print("Could not export the public key. Check if a YubiKey is inserted")
return
if path is None:
Expand Down
22 changes: 15 additions & 7 deletions taf/keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,9 @@ def _load_and_append_yubikeys(
hide_already_loaded_message=hide_already_loaded_message,
)
if public_key is not None and public_key not in yubikeys:
signer = YkSigner(public_key, partial(yk_secrets_handler, serial_num=serial_num))
signer = YkSigner(
public_key, partial(yk_secrets_handler, serial_num=serial_num)
)
yubikeys.append(signer)
taf_logger.info(f"Successfully loaded {key_name} from inserted YubiKey")
return True
Expand Down Expand Up @@ -315,7 +317,7 @@ def setup_roles_keys(
raise SigningError("Cannot set up roles keys. Role name not specified")
yubikey_keys = []
keystore_signers = []
yubikey_signers= []
yubikey_signers = []

yubikey_ids = role.yubikey_ids
if yubikey_ids is None:
Expand Down Expand Up @@ -385,7 +387,9 @@ def _setup_yubikey_roles_keys(
key_size,
)
loaded_keys_num += 1
signer = YkSigner(public_key, partial(yk_secrets_handler, serial_num=serial_num))
signer = YkSigner(
public_key, partial(yk_secrets_handler, serial_num=serial_num)
)
signers.append(signer)

if loaded_keys_num < role.threshold:
Expand All @@ -398,11 +402,15 @@ def _setup_yubikey_roles_keys(
and not users_yubikeys_details[key_id].present
):
continue
serial_num = _load_and_verify_yubikey(yubikeys, role.name, key_id, public_key)
serial_num = _load_and_verify_yubikey(
yubikeys, role.name, key_id, public_key
)
if serial_num:
loaded_keys_num += 1
loaded_keys.append(key_id)
signer = YkSigner(public_key, partial(yk_secrets_handler, serial_num=serial_num))
signer = YkSigner(
public_key, partial(yk_secrets_handler, serial_num=serial_num)
)
signers.append(signer)
if loaded_keys_num == role.threshold:
break
Expand Down Expand Up @@ -498,7 +506,7 @@ def _setup_yubikey(
scheme: Optional[str] = DEFAULT_RSA_SIGNATURE_SCHEME,
certs_dir: Optional[Union[Path, str]] = None,
key_size: int = 2048,
) -> Dict:
) -> Tuple[Dict, str]:
print(f"Registering keys for {key_name}")
while True:
use_existing = click.confirm("Do you want to reuse already set up Yubikey?")
Expand Down Expand Up @@ -532,7 +540,7 @@ def _setup_yubikey(

def _load_and_verify_yubikey(
yubikeys: Optional[Dict], role_name: str, key_name: str, public_key
) -> bool:
) -> Optional[str]:
if not click.confirm(f"Sign using {key_name} Yubikey?"):
return False
while True:
Expand Down
9 changes: 6 additions & 3 deletions taf/tests/tuf/test_keys/test_yk.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@

def test_fake_yk(mocker):
"""Test public key export and signing with fake Yubikey."""
mocker.patch('taf.yubikey.export_piv_pub_key', return_value=_PUB)
mocker.patch('taf.yubikey.sign_piv_rsa_pkcs1v15', return_value=_SIG)
mocker.patch("taf.yubikey.export_piv_pub_key", return_value=_PUB)
mocker.patch("taf.yubikey.sign_piv_rsa_pkcs1v15", return_value=_SIG)

from taf.tuf.keys import YkSigner

key = YkSigner.import_()
signer = YkSigner(key, lambda sec: None)

Expand All @@ -37,6 +38,7 @@ def test_fake_yk(mocker):
with pytest.raises(UnverifiedSignatureError):
key.verify_signature(sig, _NOT_DATA)


@pytest.mark.skipif(
not os.environ.get("REAL_YK"),
reason="Run test with REAL_YK=1 (test will prompt for pin)",
Expand All @@ -48,10 +50,11 @@ def sec_handler(secret_name: str) -> str:
return getpass(f"Enter {secret_name}: ")

from taf.tuf.keys import YkSigner

key = YkSigner.import_()
signer = YkSigner(key, sec_handler)

sig = signer.sign(_DATA)
key.verify_signature(sig, _DATA)
with pytest.raises(UnverifiedSignatureError):
key.verify_signature(sig, _NOT_DATA)
key.verify_signature(sig, _NOT_DATA)
36 changes: 2 additions & 34 deletions taf/tuf/keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa

from taf import YubikeyMissingLibrary
from taf.constants import DEFAULT_RSA_SIGNATURE_SCHEME


Expand Down Expand Up @@ -216,6 +215,7 @@ def import_(cls) -> SSlibKey:
"""
# TODO: export pyca/cryptography key to avoid duplicate deserialization
from taf.yubikey import export_piv_pub_key

pem = export_piv_pub_key()
pub = load_pem_public_key(pem)
return _from_crypto(pub)
Expand All @@ -225,6 +225,7 @@ def sign(self, payload: bytes) -> Signature:
# TODO: openlawlibrary/taf#515
# sig = sign_piv_rsa_pkcs1v15(payload, pin, self.public_key.keyval["public"])
from taf.yubikey import sign_piv_rsa_pkcs1v15

sig = sign_piv_rsa_pkcs1v15(payload, pin)
return Signature(self.public_key.keyid, sig.hex())

Expand Down Expand Up @@ -259,36 +260,3 @@ def root_signature_provider(signature_dict, key_id, _key, _data):
from binascii import hexlify

return {"keyid": key_id, "sig": hexlify(signature_dict.get(key_id)).decode()}


def yubikey_signature_provider(name, key_id, key, data): # pylint: disable=W0613
"""
A signatures provider which asks the user to insert a yubikey
Useful if several yubikeys need to be used at the same time
"""
from binascii import hexlify

def _check_key_and_get_pin(expected_key_id):
try:
inserted_key = yk.get_piv_public_key_tuf()
if expected_key_id != inserted_key["keyid"]:
return None
serial_num = yk.get_serial_num(inserted_key)
pin = yk.get_key_pin(serial_num)
if pin is None:
pin = yk.get_and_validate_pin(name)
return pin
except Exception:
return None

while True:
# check if the needed YubiKey is inserted before asking the user to do so
# this allows us to use this signature provider inside an automated process
# assuming that all YubiKeys needed for signing are inserted
pin = _check_key_and_get_pin(key_id)
if pin is not None:
break
input(f"\nInsert {name} and press enter")

signature = yk.sign_piv_rsa_pkcs1v15(data, pin)
return {"keyid": key_id, "sig": hexlify(signature).decode()}
2 changes: 0 additions & 2 deletions taf/yubikey.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding

# TODO: Remove legacy imports
# from tuf.repository_tool import import_rsakey_from_pem
from taf.tuf.keys import get_sslib_key_from_value
from ykman.device import list_all_devices
from yubikit.core.smartcard import SmartCardConnection
Expand Down

0 comments on commit 385a0be

Please sign in to comment.