This repository has been archived by the owner on Feb 5, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyubikey_piv_resetter.py
66 lines (50 loc) · 2.02 KB
/
yubikey_piv_resetter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import logging
from subprocess import CompletedProcess
from app.yubikey_details import YubikeyDetails
import subprocess
logger = logging.getLogger()
class YubiKeyPIVResetter:
"""IMPORTANT NOTE: Use this class carefully, this will reset the whole PIV module of the selected YubiKey"""
def _is_complete(self, result: CompletedProcess) -> bool:
if result.stdout is None:
return False
actual: str = result.stdout.decode()
expected_in_stdout = "Reset complete."
ok = expected_in_stdout in actual
return ok
def _run_reset(self, yubikey_serial: str) -> CompletedProcess:
cmdargs = [
"ykman",
f"--device={yubikey_serial} ", # We need the extra space for the command to work
"piv",
"reset",
"--force",
]
result = subprocess.run(cmdargs, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
return result
def _validate_cmd_result(self, result: CompletedProcess):
decoded = result.stdout.decode()
if decoded == "":
raise Exception("The command returned an empty string")
if "ERROR: Failed connecting to a YubiKey with serial:" in decoded:
raise Exception("Selected Yubikey could not be found.")
def _log_result(self, resetted: bool):
if resetted:
logger.info("Yubikey successfully resetted")
def reset(self, yubikey: YubikeyDetails) -> bool:
logger.info(
f"Resetting the PIV module for Yubikey with serial {yubikey.serial}...",
)
result: CompletedProcess = self._run_reset(yubikey.serial)
self._validate_cmd_result(result)
ok = self._is_complete(result)
if not ok:
logger.warning(
"Yubikey was not reset. Find the stdout below.",
)
logger.info(result.stdout.decode())
else:
logger.info(
f"Yubikey with serial {yubikey.serial} was successfully reset",
)
return ok