Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -639,6 +639,10 @@ An anonymous request to a page of the web console goes to the login page before

The MDM check-in, the OTA enrollment and the DEP web enrollment endpoints refuse a malformed request with a 4xx error now, and not with a 500 error. A signature with no signer, with a signer that matches no certificate, or with a signer that is identified by its subject key identifier, is refused as a signature that is not valid. Before, the first one was read as a verified signature with no certificate, and the other two gave an error. The DEP web enrollment custom views and profile answer 404 to a request without an enrollment in the session.

`rewrap_secrets` saves only the fields that it rewraps now, and does not save an object that has no change. Before, it saved all the fields of all the objects, and set the `updated_at` field of each object to the time of the rewrap.

`rewrap_secrets` rewraps the secrets in the kwargs of the MDM commands now: the PIN of the `DeviceLock` and `EraseDevice` commands, the password of the `AccountConfiguration`, `SetAutoAdminPassword`, `SetRecoveryLock` and `SetFirmwarePassword` commands, and the encryption key of the `RotateFileVaultKey` command. Before, these secrets stayed encrypted with the old secret engine. After the removal of this engine, Zentral could not send or acknowledge a command that was still in the queue, and could not decrypt the FileVault PRK that a device returned for a `RotateFileVaultKey` command.


## 2026.5

Expand Down
17 changes: 15 additions & 2 deletions server/base/management/commands/rewrap_secrets.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
logger = logging.getLogger("zentral.server.base.management.commands.rewrap_secrets")


def get_field_values(obj):
return {field.name: field.value_from_object(obj) for field in obj._meta.concrete_fields}


class Command(BaseCommand):
help = 'Rewrap the DB secrets using the default secret engine'

Expand All @@ -20,10 +24,19 @@ def handle(self, **options):
for content_type in ContentType.objects.all():
model_class = content_type.model_class()
if hasattr(model_class, "rewrap_secrets"):
qs = content_type.get_all_objects_for_this_type()
if hasattr(model_class, "rewrap_secrets_queryset"):
qs = model_class.rewrap_secrets_queryset()
else:
qs = content_type.get_all_objects_for_this_type()
print(f"{model_class.__name__}:", qs.count(), "objects to update")
if not dry_run:
with transaction.atomic():
for obj in tqdm(qs.iterator(), total=qs.count()):
# rewrap_secrets() assigns new values to the fields, it does not mutate them,
# so the old values are compared to find the fields to save. updated_at is not one of them.
old_values = get_field_values(obj)
obj.rewrap_secrets()
super(model_class, obj).save()
update_fields = [name for name, value in get_field_values(obj).items()
if value != old_values[name]]
if update_fields:
super(model_class, obj).save(update_fields=update_fields)
8 changes: 4 additions & 4 deletions tests/mdm/test_command_audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ def setUpTestData(cls):
# the policy itself

def test_no_encrypted_kwarg_is_missing_from_this_list(self):
# get_secret_engine_kwargs() declares the encrypted field name in each command
# get_secret_engine_kwargs() gets the encrypted field name in each command
# module. Anything new there has to be classified, or it would be serialized
# verbatim the moment somebody adds it to audit_public_kwargs.
found = set()
for path in glob.glob("zentral/contrib/mdm/commands/*.py"):
found.update(re.findall(r"""field=["'](\w+)["']""", open(path).read()))
self.assertEqual(found - ENCRYPTED_KWARGS, set())
found.update(re.findall(r"""get_secret_engine_kwargs\([\w.]+, ["'](\w+)["']\)""", open(path).read()))
self.assertEqual(found, ENCRYPTED_KWARGS)

def test_encrypted_kwargs_are_never_public(self):
for db_name, command_class in registered_commands.items():
Expand All @@ -49,7 +49,7 @@ def test_no_command_class_declares_a_kwarg_twice(self):
for db_name, command_class in registered_commands.items():
with self.subTest(db_name):
self.assertEqual(
set(command_class.audit_public_kwargs) & set(command_class.audit_secret_kwargs),
set(command_class.audit_public_kwargs) & set(command_class.secret_kwargs),
set()
)

Expand Down
161 changes: 161 additions & 0 deletions tests/mdm/test_command_rewrap_secrets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
from contextlib import redirect_stderr, redirect_stdout
from io import StringIO
import uuid
from django.core.management import call_command
from django.test import TestCase
from django.utils.crypto import get_random_string
from zentral.contrib.inventory.models import MetaBusinessUnit
from zentral.contrib.mdm.commands import (AccountConfiguration, DeviceInformation, DeviceLock, EraseDevice,
RotateFileVaultKey, SetAutoAdminPassword, SetFirmwarePassword,
SetRecoveryLock)
from zentral.contrib.mdm.commands.base import get_secret_engine_kwargs, load_command, registered_commands
from zentral.contrib.mdm.models import DeviceCommand, UserCommand
from zentral.core.secret_engines import decrypt, encrypt, secret_engines

from .utils import force_dep_enrollment_session, force_enrolled_user


SECRET_COMMANDS = {
AccountConfiguration: "admin_password",
DeviceLock: "PIN",
EraseDevice: "PIN",
RotateFileVaultKey: "encryption_key",
SetAutoAdminPassword: "new_password",
SetFirmwarePassword: "new_password",
SetRecoveryLock: "new_password",
}


class CommandRewrapSecretsTestCase(TestCase):
@classmethod
def setUpTestData(cls):
cls.mbu = MetaBusinessUnit.objects.create(name=get_random_string(12))
cls.mbu.create_enrollment_business_unit()
cls.session, _, _ = force_dep_enrollment_session(cls.mbu, completed=True)
cls.enrolled_device = cls.session.enrolled_device

def setUp(self):
super().setUp()
secret_engines.load_config({})
self.addCleanup(secret_engines.load_config, {})

def _load_fernet_engine(self):
secret_engines.load_config({
"fernet": {"backend": "zentral.core.secret_engines.backends.fernet",
"passwords": ["undeuxtrois"]}
})

def _force_command(self, command_class, kwargs=None, secret=None, model=DeviceCommand, target=None):
command_uuid = uuid.uuid4()
kwargs = dict(kwargs or {})
if secret is not None:
key = SECRET_COMMANDS[command_class]
kwargs[key] = encrypt(secret, **get_secret_engine_kwargs(command_uuid, key))
if target is None:
target = {"enrolled_device": self.enrolled_device}
return model.objects.create(uuid=command_uuid, name=command_class.get_db_name(), kwargs=kwargs, **target)

def _decrypt(self, db_command, key):
return decrypt(db_command.kwargs[key], **get_secret_engine_kwargs(db_command.uuid, key))

# the declarations

def test_secret_commands(self):
self.assertEqual(
{command_class: command_class.secret_kwargs
for command_class in registered_commands.values()
if command_class.secret_kwargs},
{command_class: (key,) for command_class, key in SECRET_COMMANDS.items()}
)

# rewrap_kwargs

def test_rewrap_kwargs(self):
self._load_fernet_engine()
command_uuid = uuid.uuid4()
encrypted_pin = encrypt(b"123456", **get_secret_engine_kwargs(command_uuid, "PIN"))
kwargs = {"PIN": encrypted_pin, "Message": "lost"}
rewrapped_kwargs = DeviceLock.rewrap_kwargs(command_uuid, kwargs)
self.assertEqual(kwargs, {"PIN": encrypted_pin, "Message": "lost"})
self.assertEqual(set(rewrapped_kwargs), {"PIN", "Message"})
self.assertNotEqual(rewrapped_kwargs["PIN"], encrypted_pin)
self.assertEqual(decrypt(rewrapped_kwargs["PIN"], **get_secret_engine_kwargs(command_uuid, "PIN")),
b"123456")
self.assertEqual(rewrapped_kwargs["Message"], "lost")

def test_rewrap_kwargs_empty_value(self):
self.assertEqual(SetRecoveryLock.rewrap_kwargs(uuid.uuid4(), {"new_password": ""}), {"new_password": ""})

# rewrap_secrets

def test_rewrap_secrets(self):
for command_class, key in SECRET_COMMANDS.items():
with self.subTest(command_class.request_type):
secret_engines.load_config({})
secret = get_random_string(12).encode("utf-8")
db_command = self._force_command(command_class, kwargs={"public": "yes"}, secret=secret)
self.assertEqual(db_command.kwargs[key].split("$")[0], "noop")
self._load_fernet_engine()
db_command.rewrap_secrets()
self.assertEqual(db_command.kwargs[key].split("$")[0], "fernet")
self.assertEqual(self._decrypt(db_command, key), secret)
self.assertEqual(db_command.kwargs["public"], "yes")

def test_rewrap_secrets_loaded_by_the_command(self):
db_command = self._force_command(DeviceLock, secret=b"123456")
self._load_fernet_engine()
db_command.rewrap_secrets()
db_command.save()
db_command.refresh_from_db()
self.assertEqual(db_command.kwargs["PIN"].split("$")[0], "fernet")
self.assertEqual(load_command(db_command).load_pin(), "123456")

def test_rewrap_secrets_unknown_command(self):
db_command = DeviceCommand.objects.create(
uuid=uuid.uuid4(),
name=get_random_string(12),
kwargs={"PIN": "noop$MTIzNDU2"},
enrolled_device=self.enrolled_device,
)
self._load_fernet_engine()
db_command.rewrap_secrets()
self.assertEqual(db_command.kwargs, {"PIN": "noop$MTIzNDU2"})

# rewrap_secrets_queryset

def test_device_command_rewrap_secrets_queryset(self):
expected_commands = [self._force_command(command_class, secret=b"yolo") for command_class in SECRET_COMMANDS]
self._force_command(EraseDevice, kwargs={"PreserveDataPlan": True})
self._force_command(DeviceInformation)
DeviceCommand.objects.create(uuid=uuid.uuid4(), name=get_random_string(12), kwargs={"PIN": "noop$MTIzNDU2"},
enrolled_device=self.enrolled_device)
self.assertEqual(
sorted(DeviceCommand.rewrap_secrets_queryset().values_list("pk", flat=True)),
sorted(db_command.pk for db_command in expected_commands)
)

def test_user_command_rewrap_secrets_queryset(self):
enrolled_user = force_enrolled_user(self.enrolled_device)
self._force_command(DeviceInformation, model=UserCommand, target={"enrolled_user": enrolled_user})
self.assertEqual(UserCommand.rewrap_secrets_queryset().count(), 0)
db_command = self._force_command(DeviceLock, secret=b"123456",
model=UserCommand, target={"enrolled_user": enrolled_user})
self.assertEqual(list(UserCommand.rewrap_secrets_queryset()), [db_command])

# management command

def test_rewrap_secrets_management_command(self):
db_command = self._force_command(DeviceLock, kwargs={"Message": "lost"}, secret=b"123456")
other_db_command = self._force_command(DeviceInformation, kwargs={"yolo": "fomo"})
self._load_fernet_engine()
stdout = StringIO()
with redirect_stdout(stdout), redirect_stderr(StringIO()):
call_command("rewrap_secrets")
self.assertIn("DeviceCommand: 1 objects to update", stdout.getvalue())
self.assertIn("UserCommand: 0 objects to update", stdout.getvalue())
updated_db_command = DeviceCommand.objects.get(pk=db_command.pk)
self.assertEqual(updated_db_command.kwargs["PIN"].split("$")[0], "fernet")
self.assertEqual(self._decrypt(updated_db_command, "PIN"), b"123456")
self.assertEqual(updated_db_command.kwargs["Message"], "lost")
self.assertEqual(updated_db_command.updated_at, db_command.updated_at)
self.assertEqual(DeviceCommand.objects.get(pk=other_db_command.pk).updated_at, other_db_command.updated_at)
96 changes: 96 additions & 0 deletions tests/server_base/test_management_command_rewrap_secrets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
from contextlib import redirect_stderr, redirect_stdout
from io import StringIO
from unittest.mock import patch
from django.core.management import call_command
from django.db import models
from django.test import TestCase
from django.utils.crypto import get_random_string
from zentral.contrib.jamf.models import JamfInstance
from zentral.core.secret_engines import secret_engines


class RewrapSecretsManagementCommandTestCase(TestCase):
def setUp(self):
super().setUp()
secret_engines.load_config({})
self.addCleanup(secret_engines.load_config, {})

def _force_jamf_instance(self):
jamf_instance = JamfInstance.objects.create(
host="{}.example.com".format(get_random_string(12)),
port=443,
path="/JSSResource",
user=get_random_string(12)
)
jamf_instance.set_password(get_random_string(12))
super(JamfInstance, jamf_instance).save()
jamf_instance.refresh_from_db()
return jamf_instance

def _load_fernet_engine(self):
secret_engines.load_config({
"fernet": {"backend": "zentral.core.secret_engines.backends.fernet",
"passwords": ["undeuxtrois"]}
})

def _call_command(self, *args):
stdout = StringIO()
original_save = models.Model.save
with (patch.object(models.Model, "save", autospec=True, side_effect=original_save) as save,
redirect_stdout(stdout),
redirect_stderr(StringIO())):
call_command("rewrap_secrets", *args)
return stdout.getvalue(), save

def _jamf_instance_save_calls(self, save, jamf_instance):
return [c for c in save.call_args_list
if isinstance(c.args[0], JamfInstance) and c.args[0].pk == jamf_instance.pk]

def test_rewrap_secrets_saves_only_the_rewrapped_fields(self):
jamf_instance = self._force_jamf_instance()
password = jamf_instance.get_password()
self._load_fernet_engine()
stdout, save = self._call_command()
self.assertIn("JamfInstance: 1 objects to update", stdout)
save_calls = self._jamf_instance_save_calls(save, jamf_instance)
self.assertEqual(len(save_calls), 1)
self.assertEqual(save_calls[0].kwargs, {"update_fields": ["password"]})
updated_jamf_instance = JamfInstance.objects.get(pk=jamf_instance.pk)
self.assertEqual(updated_jamf_instance.password.split("$")[0], "fernet")
self.assertEqual(updated_jamf_instance.get_password(), password)
self.assertEqual(updated_jamf_instance.updated_at, jamf_instance.updated_at)
self.assertEqual(updated_jamf_instance.version, jamf_instance.version)

def test_rewrap_secrets_does_not_save_unchanged_objects(self):
jamf_instance = self._force_jamf_instance()
stdout, save = self._call_command()
self.assertIn("JamfInstance: 1 objects to update", stdout)
self.assertEqual(self._jamf_instance_save_calls(save, jamf_instance), [])
updated_jamf_instance = JamfInstance.objects.get(pk=jamf_instance.pk)
self.assertEqual(updated_jamf_instance.password, jamf_instance.password)
self.assertEqual(updated_jamf_instance.updated_at, jamf_instance.updated_at)

def test_rewrap_secrets_queryset(self):
jamf_instance = self._force_jamf_instance()
skipped_jamf_instance = self._force_jamf_instance()
self._load_fernet_engine()
with patch.object(JamfInstance, "rewrap_secrets_queryset", create=True,
return_value=JamfInstance.objects.filter(pk=jamf_instance.pk)):
stdout, save = self._call_command()
self.assertIn("JamfInstance: 1 objects to update", stdout)
self.assertEqual(len(self._jamf_instance_save_calls(save, jamf_instance)), 1)
self.assertEqual(self._jamf_instance_save_calls(save, skipped_jamf_instance), [])
self.assertEqual(JamfInstance.objects.get(pk=jamf_instance.pk).password.split("$")[0], "fernet")
self.assertEqual(
JamfInstance.objects.get(pk=skipped_jamf_instance.pk).password,
skipped_jamf_instance.password
)

def test_rewrap_secrets_dry_run(self):
jamf_instance = self._force_jamf_instance()
self._load_fernet_engine()
stdout, save = self._call_command("--dry-run")
self.assertIn("JamfInstance: 1 objects to update", stdout)
self.assertEqual(self._jamf_instance_save_calls(save, jamf_instance), [])
updated_jamf_instance = JamfInstance.objects.get(pk=jamf_instance.pk)
self.assertEqual(updated_jamf_instance.password, jamf_instance.password)
12 changes: 4 additions & 8 deletions zentral/contrib/mdm/commands/account_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,16 @@
from zentral.contrib.mdm.payloads import substitute_variables
from zentral.core.secret_engines import decrypt_str, encrypt_str
from zentral.utils.passwords import build_password_hash_dict, serialize_password_hash_dict
from .base import register_command, Command
from .base import register_command, Command, get_secret_engine_kwargs
from .set_auto_admin_password import generate_password


logger = logging.getLogger("zentral.contrib.mdm.commands.account_configuration")


def get_secret_engine_kwargs(uuid):
return {"model": "mdm.devicecommand", "field": "admin_password", "uuid": str(uuid)}


class AccountConfiguration(Command):
request_type = "AccountConfiguration"
audit_secret_kwargs = ("admin_password",)
secret_kwargs = ("admin_password",)

@staticmethod
def verify_channel_and_device(channel, enrolled_device):
Expand All @@ -37,13 +33,13 @@ def create_for_target_and_dep_enrollment(cls, target, dep_enrollment):
uuid = uuid4()
if dep_enrollment.has_auto_admin():
password = generate_password(complexity=dep_enrollment.admin_password_complexity)
kwargs = {"admin_password": encrypt_str(password, **get_secret_engine_kwargs(uuid))}
kwargs = {"admin_password": encrypt_str(password, **get_secret_engine_kwargs(uuid, "admin_password"))}
return super().create_for_target(target, kwargs=kwargs, uuid=uuid)

def load_admin_password(self):
encrypted_admin_password = self.db_command.kwargs.get("admin_password")
if encrypted_admin_password:
return decrypt_str(encrypted_admin_password, **get_secret_engine_kwargs(self.uuid))
return decrypt_str(encrypted_admin_password, **get_secret_engine_kwargs(self.uuid, "admin_password"))

def build_command(self):
if not isinstance(self.enrollment_session, DEPEnrollmentSession):
Expand Down
Loading