fix: apply updated root passwords through cloud-init chpasswd

dev
admin 2 months ago
parent 95787ca9c3
commit 8829ad009d

@ -357,6 +357,10 @@ def test_password_seed_sets_root_hash_and_enables_ssh_password_login():
assert user_data["users"][0]["lock_passwd"] is False
assert user_data["users"][0]["hashed_passwd"] == password_hash
assert "ssh_authorized_keys" not in user_data["users"][0]
assert user_data["chpasswd"] == {
"expire": False,
"users": [{"name": "root", "password": password_hash, "type": "hash"}],
}
sshd_dropin = user_data["write_files"][0]
assert sshd_dropin["path"] == "/etc/ssh/sshd_config.d/00-virsh-panel-root.conf"
assert "PermitRootLogin yes" in sshd_dropin["content"]
@ -382,6 +386,7 @@ def test_seed_allows_root_password_and_ssh_key_together():
assert root["ssh_authorized_keys"] == [PUBLIC_KEY]
assert root["hashed_passwd"] == password_hash
assert user_data["ssh_pwauth"] is True
assert user_data["chpasswd"]["users"][0]["password"] == password_hash
assert "PermitRootLogin yes" in user_data["write_files"][0]["content"]
assert "PasswordAuthentication yes" in user_data["write_files"][0]["content"]
assert GUEST_PASSWORD.encode() not in seed
@ -485,6 +490,7 @@ def test_replace_seed_settings_rotates_generation_without_exposing_password():
assert GUEST_PASSWORD.encode() not in changed
assert b"Another-strong-password-2026!" not in changed
assert user_data["ssh_pwauth"] is True
assert user_data["chpasswd"]["users"][0]["type"] == "hash"
assert _meta_data(changed)["local-hostname"] == "node.example"
assert _meta_data(changed)["instance-id"].startswith("virt-cloud-settings-")
assert read_seed_network(changed) == read_seed_network(seed)

@ -347,6 +347,8 @@ def build_seed_iso(
# current network-config on every boot.
"updates": {"network": {"when": ["boot"]}},
}
if use_password:
_set_root_chpasswd(user_data, network["root_password_hash"])
if debian12_network_fix:
# NoCloud normally consumes user-data in its network stage. Debian 12
# can wait for a still-disabled systemd-networkd before reaching that
@ -782,6 +784,58 @@ def _replace_root_authorized_keys(config: dict[str, Any], public_key: str) -> No
write_files.append(replacement)
def _set_root_chpasswd(config: dict[str, Any], root_password_hash: str) -> None:
"""Set a hashed root password through cloud-init's password module.
``users[].hashed_passwd`` is retained for older cloud-init releases, but
recent releases have reported existing users as locked even when that
field is paired with ``lock_passwd: false``. The ``chpasswd`` module runs
after user creation and applies the hash to an already-existing root
account, which makes password replacement consistent across supported
AlmaLinux, Debian and Ubuntu images. The hash is never converted back to
plaintext.
"""
try:
_validate_guest_auth("", root_password_hash)
except ValueError as exc:
raise ValueError("root 密码哈希格式无效") from exc
config["chpasswd"] = {
"expire": False,
"users": [{
"name": "root",
"password": root_password_hash,
"type": "hash",
}],
}
def _remove_root_chpasswd(config: dict[str, Any]) -> None:
"""Remove a panel-managed root chpasswd entry when password auth is off."""
chpasswd = config.get("chpasswd")
if chpasswd is None:
return
if not isinstance(chpasswd, dict):
raise ValueError("原 cloud-init 密码配置格式无效")
users = chpasswd.get("users")
if users is None:
config.pop("chpasswd", None)
return
if not isinstance(users, list) or len(users) > 32:
raise ValueError("原 cloud-init 密码配置格式无效")
root_count = sum(
1 for item in users
if isinstance(item, dict) and item.get("name") == "root"
)
if root_count > 1:
raise ValueError("原 cloud-init root 密码配置重复")
remaining = [item for item in users
if not (isinstance(item, dict) and item.get("name") == "root")]
if remaining:
chpasswd["users"] = remaining
else:
config.pop("chpasswd", None)
def replace_seed_settings(
seed: bytes,
*,
@ -844,6 +898,10 @@ def replace_seed_settings(
# Do not silently preserve a malformed unlocked root record.
raise ValueError("原 cloud-init root 密码配置格式无效")
root["lock_passwd"] = not use_password
if use_password:
_set_root_chpasswd(user_data, root["hashed_passwd"])
else:
_remove_root_chpasswd(user_data)
_update_root_sshd_config(user_data, use_password=use_password)
user_data = json.loads(json.dumps(user_data, ensure_ascii=True))
metadata["instance-id"] = f"virt-cloud-settings-{uuid.uuid4().hex}"

Loading…
Cancel
Save