Skip to content

Commit

Permalink
Add support for factory reset command
Browse files Browse the repository at this point in the history
  • Loading branch information
sosthene-nitrokey committed Nov 15, 2023
1 parent 815bb68 commit 85bbda0
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
7 changes: 7 additions & 0 deletions pynitrokey/cli/nk3/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,13 @@ def version(ctx: Context) -> None:
local_print(version)


@nk3.command()
@click.pass_obj
def factory_reset(ctx: Context) -> None:
with ctx.connect_device() as device:
device.factory_reset()


@nk3.command()
@click.pass_obj
def wink(ctx: Context) -> None:
Expand Down
38 changes: 38 additions & 0 deletions pynitrokey/nk3/admin_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class AdminCommand(Enum):
TEST_SE050 = 0x81
GET_CONFIG = 0x82
SET_CONFIG = 0x83
FACTORY_RESET = 0x84


@enum.unique
Expand Down Expand Up @@ -57,6 +58,31 @@ class Status:
variant: Optional[Variant] = None


@enum.unique
class FactoryResetStatus(Enum):
SUCCESS = 0
NOT_CONFIRMED = 0x01
APP_NOT_ALLOWED = 0x02
APP_FAILED_PARSE = 0x03

@classmethod
def from_int(cls, i: int) -> Optional["FactoryResetStatus"]:
for status in FactoryResetStatus:
if status.value == i:
return status
return None

@classmethod
def check(cls, i: int, msg: str) -> None:
status = FactoryResetStatus.from_int(i)
if status != FactoryResetStatus.SUCCESS:
if status:
error = str(status)
else:
error = f"unknown error {i:x}"
raise Exception(f"{msg}: {error}")


@enum.unique
class ConfigStatus(Enum):
SUCCESS = 0
Expand Down Expand Up @@ -148,3 +174,15 @@ def set_config(self, key: str, value: str) -> None:
reply = self._call(AdminCommand.SET_CONFIG, data=request, response_len=1)
assert reply
ConfigStatus.check(reply[0], "Failed to set config value")

def factory_reset(self) -> None:
try:
reply = self._call(AdminCommand.FACTORY_RESET, response_len=1)
assert reply
except OSError as e:
if e.errno == 5:
self.device.logger.debug("ignoring OSError after reboot", exc_info=e)
return
else:
raise e
FactoryResetStatus.check(reply[0], "Failed to factory reset the device")
3 changes: 3 additions & 0 deletions pynitrokey/nk3/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,9 @@ def uuid(self) -> Optional[Uuid]:
def version(self) -> Version:
return self.admin.version()

def factory_reset(self) -> None:
self.admin.factory_reset()

def wink(self) -> None:
self.device.wink()

Expand Down

0 comments on commit 85bbda0

Please sign in to comment.