Skip to content

{vm-repair} Fixes a command-injection vulnerability - #10443

Merged
William (william051200) merged 27 commits into
Azure:mainfrom
william051200:fix-vm-repair
Oct 29, 2026
Merged

William (william051200) merged 27 commits into
Azure:mainfrom
william051200:fix-vm-repair

Conversation

@william051200

@william051200 William (william051200) commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

🤖 PR Validation — ⚠️ Review suggested

Breaking Changes Suppressions
️✔️ None ⚠️ 17 added

This PR adds warning or check suppressions. Fix the underlying warning where possible and justify each remaining suppression in a code comment or the PR description.

17 added suppressions
File Line Kind Code
src/vm-repair/azext_vm_repair/tests/latest/test_command_injection.py 192 skipped test @pytest.mark.skipif(os.name != 'nt', reason='batch launch is Windows-specific')
src/vm-repair/azext_vm_repair/tests/latest/test_command_injection.py 210 skipped test @pytest.mark.skipif(os.name != 'nt', reason='interpreter-based launch is Windows-specific')
src/vm-repair/azext_vm_repair/tests/latest/test_command_injection.py 223 skipped test @pytest.mark.skipif(os.name != 'nt', reason='interpreter-based launch is Windows-specific')
src/vm-repair/azext_vm_repair/tests/latest/test_command_injection.py 232 skipped test @pytest.mark.skipif(os.name != 'nt', reason='batch launch is Windows-specific')
src/vm-repair/azext_vm_repair/tests/latest/test_command_injection.py 245 skipped test @pytest.mark.skipif(os.name != 'nt', reason='interpreter-based launch is Windows-specific')
src/vm-repair/azext_vm_repair/tests/latest/test_nested_az_invocation.py 183 skipped test @pytest.mark.skipif(os.name != 'nt', reason='batch launch is Windows-specific')
src/vm-repair/azext_vm_repair/tests/latest/test_nested_az_invocation.py 191 skipped test @pytest.mark.skipif(os.name != 'nt', reason='batch launch is Windows-specific')
src/vm-repair/azext_vm_repair/tests/latest/test_nested_az_invocation.py 201 skipped test @pytest.mark.skipif(os.name != 'nt', reason='batch launch is Windows-specific')
src/vm-repair/azext_vm_repair/tests/latest/test_nested_az_invocation.py 270 skipped test @pytest.mark.skipif(
src/vm-repair/azext_vm_repair/tests/latest/test_nested_az_invocation.py 275 pylint python = Path(sys._base_executable) # pylint: disable=protected-access
src/vm-repair/azext_vm_repair/tests/latest/test_repair_utils.py 272 skipped test @pytest.mark.skipif(os.name == 'nt', reason='requires native POSIX symlink traversal')
src/vm-repair/azext_vm_repair/tests/latest/test_vm_creation.py 245 pylint response._content = json.dumps(response_body).encode('utf-8') # pylint: disable=protected-access
src/vm-repair/azext_vm_repair/tests/latest/test_vm_creation.py 246 pylint response._content_consumed = True # pylint: disable=protected-access
src/vm-repair/azext_vm_repair/vm_creation.py 29 pylint # pylint: disable=protected-access
src/vm-repair/azext_vm_repair/vm_creation.py 80 pylint namespace.cmd = namespace._cmd = command # pylint: disable=protected-access
src/vm-repair/azext_vm_repair/vm_creation.py 81 pylint invocation._validation(namespace) # pylint: disable=protected-access
src/vm-repair/azext_vm_repair/vm_creation.py 82 pylint return invocation._run_job(namespace, command) # pylint: disable=protected-access

This PR hardens command execution in vm-repair while preserving valid percent-encoded unmanaged-disk URIs.

Repair VM creation now reuses core Azure CLI validation and ARM deployment in process. Unmanaged blob operations use the Storage SDK, and unmanaged disk attachment, detachment, and OS-disk URI updates use AAZ operations. These paths pass structured values without shell parsing. Existing tag restrictions and password validation remain in place.

Remaining nested commands on Windows retain the cmd.exe/az.cmd launcher, with stricter argument validation, quoting, disabled delayed expansion, removal of inherited PYTHONPATH, and an extension-directory working directory. Linux/macOS retain their existing subprocess launch path. Secret masking and asynchronous behavior remain supported.

Restore and NIC reset validate follow-up arguments before disruptive changes, and restore failures provide stage-specific recovery guidance. This release requires Azure CLI 2.90.0 or later.


This checklist is used to make sure that common guidelines for a pull request are followed.

Related command

General Guidelines

  • Have you run azdev style <YOUR_EXT> locally? (pip install azdev required)
  • Have you run python scripts/ci/test_index.py -q locally? (pip install azdev required)
  • My extension version conforms to the Extension version schema

For new extensions:

About Extension Publish

There is a pipeline to automatically build, upload and publish extension wheels.
Once your pull request is merged into main branch, a new pull request will be created to update src/index.json automatically.
You only need to update the version information in file setup.py and historical information in file HISTORY.rst in your PR but do not modify src/index.json.

Copilot AI balanced review requested due to automatic review settings October 7, 2026 06:52
@microsoft-github-policy-service microsoft-github-policy-service Bot added the Auto-Assign Auto assign by bot label Oct 7, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Command expansion remains unguarded, and validation errors can disclose sensitive parameters.

Review effort: Balanced
Findings: 2 High severity · 1 Medium severity

Open (3)
What changed in this PR

This PR hardens Windows nested Azure CLI commands in vm-repair by adding shared token validation.

Changes:

  • Rejects quotes and control characters before Windows command execution.
  • Reuses validation for tags and adds injection regression tests.
  • Updates the version and release notes to 2.4.6.
File Description
src/​vm-repair/​setup.py Bumps version to 2.4.6.
src/​vm-repair/​HISTORY.rst Documents Windows command hardening.
src/​vm-repair/​azext_vm_repair/​tests/​latest/​test_osdisk_uri_injection.py Adds unmanaged-disk injection regression tests.
src/​vm-repair/​azext_vm_repair/​repair_utils.py Adds shared validation before Windows command execution.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Validation can reject a repaired disk URI after detachment, leaving restore unable to retry normally.

Review effort: Balanced
Findings: 1 High severity · 1 Medium severity · 1 Low severity

Open (3)
Resolved since last review (3)

Comment thread src/vm-repair/HISTORY.rst Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Secret redaction lets unsafe execution arguments bypass the Windows validation guard.

Review effort: Balanced
Findings: 2 High severity · 1 Medium severity

Open (3)
Resolved since last review (2)

Comment thread src/vm-repair/azext_vm_repair/custom.py Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

The non-leaking regression assertion must detect disclosure of the actual rejected token.

Review effort: Balanced
Findings: 1 High severity · 2 Medium severity

Open (3)
Resolved since last review (1)

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unescaped URI quotes still bypass validation and inject additional Azure CLI arguments.

3 open findings
1 resolved since last review

🧠 Review effort: Balanced


Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.

Comment thread src/vm-repair/azext_vm_repair/custom.py Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Credential rejection can occur after disk copying, leaving a billable disk outside the cleanup scope.

2 open findings
1 resolved since last review
Previously missed (1)

In code that hasn't changed since last review

Medium severity Validate VM credentials before creating disks to prevent orphaned resources

src/​vm-repair/​azext_vm_repair/​repair_utils.py:196

On a Windows host, a password such as CorrectHorse7! passes validate_vm_password, but this new guard rejects it when _create_repair_vm() validates the VM template. By then, managed-disk create() has already copied the OS disk into the source resource group (custom.py:402–428). Failure cleanup deletes only the repair resource group (custom.py:591–594), leaving the copied disk behind and accruing charges. Keep this sink-level guard, but validate the credentials or preflight the VM-create command before creating resources. Add a regression test asserting that rejected credentials cause no resource mutations.

🧠 Review effort: Balanced


Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Security-sensitive Windows launching and VM disk lifecycle changes require final human validation across supported installations.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Low severity Align PR description with validated batch launcher behavior

src/​vm-repair/​azext_vm_repair/​repair_utils.py:224

The PR description says _call_az_command() now launches the current Python interpreter with -m azure.cli, avoiding cmd.exe/az.cmd and preserving literal % and !. This implementation still launches cmd.exe/az.cmd, and _validate_legacy_tokens() rejects those characters for legacy arguments. Please update the description to reflect the validated batch launcher and distinguish it from the structured SDK/AAZ paths that preserve URI characters, so the stated security and compatibility guarantees match the code.

Review effort: Balanced

@EdwinBernal1

Copy link
Copy Markdown
Member

[P2] Preserve core argument preparation when command indexing is disabled

On supported CLI 2.91, setting AZURE_CORE_USE_COMMAND_INDEX=false makes all four creation-preparation test variants fail with a missing --vm-name, although this helper supplied the name through --name. The standard CLI invoker accepts -n in the same configuration with deployment mocked. Please preserve the core command's full preparation lifecycle under both indexed and full loading, and add the disabled-index regression. Truncating only the main command-table dictionary is not sufficient here.

Comment at CLI context copying

[P2] Isolate event-handler lists as well as invocation data

This shallow copy still shares the parent's event mapping and handler lists. On CLI 2.91 with full loading, the installed Azure DevOps loader appends its post-parse hook to the original context, even when this helper subsequently fails parsing and never deploys. Please clone the event registry and its lists, or use an independent invocation context, before loading commands. Add parent-state assertions for both success and setup-error paths.

Changes since the previous review

Previous concern or new surface Current assessment
Isolated child could not import user-site-only Azure CLI Old python -I -m path removed. Legacy operations again use a guarded batch launcher. The old failure no longer describes this implementation. The dedicated fresh-user-install test was not enabled locally; see limitations.
Working-directory and inherited PYTHONPATH replacement Launcher now removes PYTHONPATH, sets safe-path behavior, and starts from the extension directory. Current real-process working-directory and import-path tests pass under CLI 2.91. This is not the earlier bootstrap suggestion.
Shell-sensitive values in VM creation VM creation uses structured in-process argument preparation and ARM deployment. Credentials and tags are inserted as structured values rather than shell command text.
Unmanaged URI percent encoding and shell metacharacters Blob operations use the Storage SDK; attachment, detachment, and source URI updates use AAZ callbacks. Corresponding tests pass.
Image-reference revalidation during unmanaged restore Source-update callback now clears the image reference, as do the new attach/detach helpers.
Relative custom-script paths after child-directory hardening Paths are resolved before subprocess execution; real-process tests cover caller and extension directories with spaces, apostrophes, parentheses, and other accepted symbols.
Credential-bearing template and HTTP debug logs New targeted logging filters and mocked real-transport tests cover validation/deployment request and response logging. These tests pass.
Minimum supported CLI Raised from 2.83.0 to 2.90.0 and documented. It is essential to assess current behavior on a supported runtime.
In-process invocation preparation and context isolation Two findings above remain.

All 19 returned review threads were resolved at inspection time. That GitHub state does not establish that the two newly reproduced configuration cases are correct.

Validation

Checks used an isolated archive of the exact reviewed head. The maintainer's dirty checkout was not modified. No packages were installed, no credentials were supplied to Azure, and no live resource lifecycle tests were run.

Check Result
Supported runtime: Azure CLI/core 2.91.0, bundled Python 3.14.7 Verified actual loaded core came from the bundled installation.
Default supported-runtime safe unit suite 252 passed, 2 skipped, 4 subtests passed; 26 warnings.
Supported-runtime creation + injection modules 157 passed, 2 subtests passed, included in the complete suite.
Supported runtime with command indexing disabled 4 creation-preparation cases failed, all with missing --vm-name.
Supported full-loader parent-state probe Added Azure DevOps post-parse handler appears in parent; deployment mock called zero times.
Standard invoker control, same supported full-loader configuration PASS, exit code 0 with validation and job execution mocked.
Older development runtime: CLI/core 2.89.0, Python 3.13.15 251 passed, 1 failed, 2 skipped, 4 subtests passed, reproduced twice; failure was parent-handler preservation. This runtime is below the PR minimum, so its failure alone is not a merge finding.
Older-runtime diagnostic control copying event registry/lists in memory 252 passed, 2 skipped, 4 subtests passed. Diagnostic only, not the unmodified PR result or a delivered fix.
Wheel build PASS, version 2.4.6. Build used the existing development packaging tools; setuptools emitted deprecation notices.
Current-head GitHub checks 23 succeeded, 1 skipped, no failed/pending check runs returned.
Legacy combined status pending with zero status contexts; distinct from check-run conclusions.
Style/linter/license/credential scan/breaking-change checks Current-head CI passed; not independently rerun locally.
Live integration tests Not run. The module containing 35 live-only scenario classes was excluded.

The bundled runtime did not have pytest/test-sdk installed, so the existing development environment's dependency directory was appended for test tooling. Azure CLI/core imports were verified to resolve to the supported bundled runtime, not the older development installation.

Skips, warnings, and limitations

  • One skip is a native POSIX symlink-traversal case on Windows.
  • One skip is the real user-site-only CLI test, which requires a separately prepared installation through VM_REPAIR_TEST_USER_BASE. No new package installation was performed for this review; do not claim a fresh user-only installation was verified.
  • Warnings include core telemetry datetime deprecations and the same three pre-existing destructor warnings in returned-warning tests.
  • Default-runtime unit success does not cover every CLI configuration. The two findings require the full loader, reached by the supported command-index configuration.
  • Minimum CLI 2.90.0 was not tested directly; local supported testing used 2.91.0.
  • No live VM/disk/NIC, storage-copy completion, or actual repair-script execution was tested.
  • No run-id, script filename, repair-script catalog mapping, or script-library source changed.
  • CI's suppression advisory primarily lists platform/fixture-specific skips and private-API access declarations. It is not itself evidence of an additional functional defect.
  • No additional high-confidence changed-line defect was confirmed.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Security-sensitive Windows launching and disk updates need human integration review, and unresolved correctness issues remain.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Medium severity Decode escaped blob names before creating source client

src/​vm-repair/​azext_vm_repair/​custom.py:488

StorageResourceIdentifier leaves URL escapes in blob, but the Storage SDK's get_blob_client() expects a decoded blob name and URL-encodes it again. For a source URI ending in os%20disk%25copy.vhd, this client requests os%2520disk%2525copy.vhd, so snapshot creation fails with BlobNotFound (or snapshots a different blob if that name exists). Decode the URI-derived name once before constructing the source client, while leaving the user-provided destination name unchanged, and cover the resulting request URL in a regression test.

Review effort: Balanced

Comment thread src/vm-repair/azext_vm_repair/custom.py Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Security-sensitive Windows execution and disruptive disk/NIC workflows warrant final human review with native-Windows and live Azure validation.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Decode the URI-derived source blob name once before constructing this SDK client. StorageResourceIdentifier.blob still contains URL escapes, while get_blob_client() expects a decoded name and encodes it again. A source URI ending in os%20disk.vhd currently produces a client URL ending in os%2520disk.vhd, so snapshot creation targets the wrong blob. Use unquote(storage_account.blob) only for the URI-derived source name, leave destination names unchanged, and add request-URL regressions for spaces, percent signs, literal escape sequences, and plus signs.

Previous findings: fixed

October 26 finding Current disposition Evidence
Full command-table loading loses VM-name argument preparation Fixed Command string is set after command-table loading; indexed/full-loader tests pass, and an independent full-loader probe with installed extensions reaches the mocked deployment handler
Nested CLI context shares parent event-handler registry/lists Fixed Registry and handler lists are copied; independent success and handled-validation-error probes preserve the parent registry contents and invocation

The independent probes used the supported installed CLI and its actual extension-loading environment, rather than relying only on the tests' empty-extension fixture. VM validation/deployment operations were mocked; no resources were created.

Other changes checked

  • Both combined repair commands remove trailing CR/LF from the TSV repair-VM identifier without silently removing embedded control characters.
  • Both commands propagate restore failure results rather than returning a success-shaped response.
  • Regression tests cover LF/CRLF/no terminator, Windows/POSIX branches, detach/update/cleanup failures, and embedded control rejection.
  • No command, parameter, default, run-id, script mapping, or authentication change was introduced in the latest four-file delta.

Validation

Check Result
Supported runtime Azure CLI/core 2.91.0, bundled Python 3.14.7
Focused creation and restore tests 56 passed
Full safe local unit suite 282 passed, 2 skipped; 4 subtests passed; 27 warnings
Independent full-loader probe with installed extensions Success and handled-validation-error cases pass; parent context unchanged
Independent actual-helper blob URL probe Three escaped-name cases reproduce the mismatch; decode-once controls pass; literal-plus behavior preserved
Wheel packaging Passed, with setuptools deprecation warnings
Head freshness Rechecked; still the reviewed commit
Live Azure operations Not run
Shared maintainer checkout Not modified

The URL probe used actual SDK client construction without making network requests. It establishes the incorrect request URL, not a live service response. The expected service impact follows from selecting a different blob name.

The full suite excluded the live scenario test module. The two skips were the POSIX-only symlink case and the opt-in actual user-site CLI integration case. Warnings included existing command-helper destructor warnings and dependency datetime deprecations. This run does not claim fresh live Azure, native POSIX, or real user-site-install validation.

This round did not rerun the complete local azdev style/linter release gates. Successful GitHub checks and local unit tests do not replace those gates.

Approval criteria

  1. Fix the source blob-name decoding issue and add request-URL regression tests.
  2. Rerun the affected storage/creation tests and the safe unit suite.
  3. Keep the already corrected full-loader, parent-context-isolation, and combined restore regressions green.
  4. Confirm required release checks and branch rules are satisfied before approval.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Security-sensitive Windows launcher parsing and direct AAZ disk operations require native Windows regression and ARM/Storage integration validation that this source-only environment cannot provide.

No open issues 🎉

Review effort: Balanced

@william051200

Copy link
Copy Markdown
Member Author

CI is failing due to pytest version incompatibility.
#10535 is addressing this.
Required to re-run CI once it merged.

cc Edwin Bernal Microsoft (@EdwinBernal1)

@william051200

Copy link
Copy Markdown
Member Author

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).

@william051200
William (william051200) merged commit aab4545 into Azure:main Oct 29, 2026
24 checks passed
@william051200
William (william051200) deleted the fix-vm-repair branch October 29, 2026 03:38
@azclibot

Copy link
Copy Markdown
Collaborator

[Release] Update index.json for extension [ vm-repair-2.4.6 ] : https://dev.azure.com/msazure/One/_build/results?buildId=188305149&view=results

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Auto-Assign Auto assign by bot X Engineering Agent Reviewed Agent reviewed this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants