Skip to content

Commit 3b7619d

Browse files
committed
fix: 安全加固 (closed #2726)
1 parent ee63e5f commit 3b7619d

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

apps/backend/agent/solution_maker.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,13 @@ def shell_quote(value: typing.Any) -> str:
4141
return shlex.quote(value)
4242

4343

44+
def normalize_host_identity_for_shell(value: typing.Any, auth_type: str) -> str:
45+
value = "" if value is None else str(value)
46+
if auth_type == constants.AuthType.KEY:
47+
value = value.replace("\r\n", "\n").replace("\r", "\n").replace("\n", "\\n")
48+
return value
49+
50+
4451
class ExecutionSolutionStepContent:
4552
def __init__(
4653
self,
@@ -795,6 +802,7 @@ def get_run_cmd_base_params(self) -> typing.List[str]:
795802
host_identity: str = (self.identity_data.password, self.identity_data.key)[
796803
self.identity_data.auth_type == constants.AuthType.KEY
797804
]
805+
host_identity = normalize_host_identity_for_shell(host_identity, self.identity_data.auth_type)
798806
login_ip: str = basic.compressed_ip(self.host.login_ip or self.host.inner_ip or self.host.inner_ipv6)
799807
run_cmd_params: typing.List[str] = [
800808
# 文件下载 / 回调服务信息

apps/backend/tests/components/collections/agent_new/test_install.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -626,6 +626,27 @@ def test_shell_solution(self):
626626
],
627627
)
628628

629+
def test_shell_solution_with_private_key(self):
630+
private_key = "-----BEGIN OPENSSH PRIVATE KEY-----\nkey-content\n-----END OPENSSH PRIVATE KEY-----"
631+
host = models.Host.objects.get(bk_host_id=self.obj_factory.bk_host_ids[0])
632+
models.IdentityData.objects.filter(bk_host_id=host.bk_host_id).update(
633+
auth_type=constants.AuthType.KEY, key=private_key
634+
)
635+
host.identity = models.IdentityData.objects.get(bk_host_id=host.bk_host_id)
636+
escaped_private_key = private_key.replace("\n", "\\n")
637+
638+
installation_tool = gen_commands(
639+
self.LEGACY_SETUP_INFO, host, mock_data_utils.JOB_TASK_PIPELINE_ID, is_uninstall=False, sub_inst_id=0
640+
)
641+
solution_parse_result: Dict[str, Any] = self.execution_solution_parser(
642+
installation_tool=installation_tool,
643+
solution_type=constants.CommonExecutionSolutionType.SHELL.value,
644+
run_cmd_param_extract={"host_solutions_json_b64": r"(.*) -HSJB (.*)"},
645+
)
646+
647+
self.assertIn(f"--host-identity='{escaped_private_key}'", solution_parse_result["cmds"][0])
648+
self.assertIn(f" -HAT {constants.AuthType.KEY}", solution_parse_result["cmds"][0])
649+
629650
def test_target_host_shell_solution(self):
630651
host = models.Host.objects.get(bk_host_id=self.obj_factory.bk_host_ids[0])
631652
installation_tool = gen_commands(

0 commit comments

Comments
 (0)