Skip to content

fix: use cleanPath instead of canonicalFilePath for sysfs check - #979

Draft
pengfeixx wants to merge 1 commit into
linuxdeepin:masterfrom
pengfeixx:agent/bugfix/374231
Draft

pengfeixx wants to merge 1 commit into
linuxdeepin:masterfrom
pengfeixx:agent/bugfix/374231

Conversation

@pengfeixx

@pengfeixx pengfeixx commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Root Cause Analysis

isSafeSysfsPath() in securityutils.cpp:48-70 uses QFileInfo::canonicalFilePath() to validate sysfs paths. This Qt API returns an empty string when the path does not exist, causing the function to return false for any non-existent path. When a PCI audio device is disabled, the device is removed from sysfs by writing to /sys<path>/remove. On the subsequent enable attempt, removeEnable() (controlinterface.cpp:573-575) calls isSafeSysfsPath() with the now-non-existent path, which returns false, blocking the enable flow and showing "启用失败".

Key evidence: repro/before.log (Case 2 reproduces the bug), controlinterface.cpp:573-575 (check fails → enable blocked), commit b0e883f5 introduced isSafeSysfsPath().

Fix

Replace QFileInfo::canonicalFilePath() with QDir::cleanPath() in isSafeSysfsPath(). cleanPath() is a pure string operation that normalizes path components (resolving . and ..) without requiring the path to exist. The existing first-layer .. check and the post-cleanPath /sys/ prefix check together maintain path traversal protection. This matches the analysis report section 10 recommendation.

Change Safety Assessment

Code Safety

  • Risk Level: Medium
  • Target line (securityutils.cpp:59) was introduced by commit b0e883f5 (a security fix for path traversal). This change corrects rather than reverts that fix — the .. check and /sys/ prefix check are both preserved.
  • All 5 callers (removeEnable, authorizedEnable, disableOutDevice, disableInDevice, unit test) are compatible or benefit. authorizedEnable() behavior unchanged for existing paths (USB devices with authorized=0 still have existing sysfs paths).

Business Impact Scope

  • PCI device enable/disable: After disabling a PCI audio adapter, right-click "Enable" now succeeds (the original bug scenario). Affected caller: removeEnable() (controlinterface.cpp:573).
  • USB device enable/disable: No behavior change — USB device sysfs paths still exist when authorized=0. Affected callers: authorizedEnable() (controlinterface.cpp:522), disableOutDevice()/disableInDevice() (enableutils.cpp).
  • Security: Path traversal attacks via .. are still rejected (first-layer check unchanged).

Verification Suggestion

  1. Disable a PCI audio adapter, then right-click "Enable" — verify it succeeds (original bug scenario).
  2. Disable/enable a USB device — verify no regression.
  3. Verify path traversal attempts with .. in device paths are still rejected.

根因分析

securityutils.cpp:48-70 的 isSafeSysfsPath() 使用 QFileInfo::canonicalFilePath() 校验 sysfs 路径。该 Qt API 在路径不存在时返回空字符串,导致函数对不存在路径返回 false。PCI 音频设备禁用时通过写入 /sys<path>/remove 从 sysfs 移除设备,再次启用时 removeEnable()(controlinterface.cpp:573-575)调用 isSafeSysfsPath() 传入已不存在的路径,安全检查返回 false,阻断启用流程,提示"启用失败"。

关键证据:repro/before.log(Case 2 复现 bug)、controlinterface.cpp:573-575(检查失败→启用被阻断)、commit b0e883f5 引入 isSafeSysfsPath()。

修复方案

将 isSafeSysfsPath() 中的 canonicalFilePath() 替换为 QDir::cleanPath()。cleanPath() 是纯字符串路径规范化操作,不要求路径存在,能解析 . 和 .. 组件。已有的第一层 .. 检查和 cleanPath() 后的 /sys/ 前缀检查共同保持路径穿越防护。与分析报告第十节方案一致。

改动安全评估

代码安全评估

  • 风险等级: 中风险
  • 目标行(securityutils.cpp:59)是 commit b0e883f5(路径穿越安全修复)引入的,本次改动修正而非撤销该修复——第一层 .. 检查和第二层 /sys/ 前缀检查均保留。
  • 5 个调用方(removeEnable、authorizedEnable、disableOutDevice、disableInDevice、单测)均兼容或受益。authorizedEnable() 对已有路径行为不变(USB 设备 authorized=0 后路径仍存在)。

业务影响范围

  • PCI 设备启用/禁用:禁用 PCI 音频适配器后右键"启用"不再失败(原始 bug 场景)。涉及调用方:removeEnable()(controlinterface.cpp:573)。
  • USB 设备启用/禁用:无行为变化——USB 设备 authorized=0 后 sysfs 路径仍存在。涉及调用方:authorizedEnable()(controlinterface.cpp:522)、disableOutDevice()/disableInDevice()(enableutils.cpp)。
  • 安全:包含 .. 的路径穿越攻击仍被拦截(第一层检查不变)。

验证建议

  1. 禁用 PCI 音频适配器后右键"启用",验证启用成功(原始 bug 场景)。
  2. 禁用/启用 USB 设备,验证无回归。
  3. 验证包含 .. 的路径穿越攻击仍被拦截。

@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: pengfeixx

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@sourcery-ai

sourcery-ai Bot commented Nov 13, 2026

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Preserve USB composite authorization handling while falling back to direct sysfs authorization writes for non-USB devices.

  • deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp L333-371

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@pengfeixx
pengfeixx marked this pull request as draft November 13, 2026 19:29

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 5 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp" line_range="333" />
<code_context>
     // A composite USB device may expose keyboard, mouse and control interfaces.
     // Keep their authorization state consistent with the selected physical device.
-    if (!UsbAuthorizationUtils::setInterfacesAuthorized(path, enable_device))
+    if (UsbAuthorizationUtils::setInterfacesAuthorized(path, enable_device)) {
+        if (enable_device) {
+            EnableSqlManager::getInstance()->removeDataFromAuthorizedTable(unique_id);
</code_context>
<issue_to_address>
**USB interfaces become inconsistent**

When a USB path is identified but `setInterfacesAuthorized()` returns false because an interface read or write fails while the selected path remains writable, `authorizedEnable()` treats that failure as a non-USB case and writes only the selected path and its parent, then updates the database and reports success; sibling interfaces remain in a different authorization state.

Distinguish unsupported non-USB paths from USB operation failures and do not run the single-path fallback for the latter.

Also at `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:342-344`.
</issue_to_address>

### Comment 2
<location path="deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp" line_range="352" />
<code_context>
+        return false;
+    }
     if (enable_device) {
+        file.write("1");
+        file.close();
+
</code_context>
<issue_to_address>
**Failed sysfs writes report success**

When a fallback sysfs `authorized` file opens but a write fails or writes fewer bytes than requested, `authorizedEnable()` ignores `QFile::write()` results, then updates the database and returns true; the caller sees success even though the requested authorization change was not made.

Check every sysfs write result and stop before updating the database or returning success when a write fails or is short.

Also at `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:360`, `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:365-366`, `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:370`.
</issue_to_address>

### Comment 3
<location path="deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp" line_range="352" />
<code_context>
+        return false;
+    }
     if (enable_device) {
+        file.write("1");
+        file.close();
+
</code_context>
<issue_to_address>
**Failed parent open leaves partial state**

When the fallback writes the target `authorized` file and a subsequent parent `authorized` file open fails, `authorizedEnable()` returns false without undoing the sysfs write; on a later parent-open failure, the parent may already have been changed. The caller sees failure while sysfs and the saved state are inconsistent.

Roll back any target and parent sysfs changes, and keep the database consistent, before returning failure.

Also at `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:355-359`, `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:363-364`.
</issue_to_address>

### Comment 4
<location path="deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp" line_range="372" />
<code_context>
+        if (enable_device) {
+            EnableSqlManager::getInstance()->removeDataFromAuthorizedTable(unique_id);
+        } else {
+            EnableSqlManager::getInstance()->insertDataToAuthorizedTable(hclass, name, path, unique_id, true, strDriver);
+        }
+        return true;
</code_context>
<issue_to_address>
**Disabled non-USB devices return enabled**

When a non-USB device is disabled through the fallback and the system restarts, `EnableUtils::disableOutDevice()` uses the USB-specific `setInterfacesAuthorized()` path, and startup restoration does not process these non-USB devices; their persisted disabled rows are skipped and the devices return enabled.

Include non-USB fallback devices in startup restoration and apply their persisted authorization state.
</issue_to_address>

### Comment 5
<location path="deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp" line_range="368" />
<code_context>
-    if (!UsbAuthorizationUtils::setInterfacesAuthorized(path, enable_device))
+    if (UsbAuthorizationUtils::setInterfacesAuthorized(path, enable_device)) {
+        if (enable_device) {
+            EnableSqlManager::getInstance()->removeDataFromAuthorizedTable(unique_id);
+        } else {
+            EnableSqlManager::getInstance()->insertDataToAuthorizedTable(hclass, name, path, unique_id, true, strDriver);
</code_context>
<issue_to_address>
**Sysfs and saved state diverge**

When a database update fails or the process stops after changing sysfs but before updating the database, the sysfs change and database update are separate, and the database helpers do not report write failures to this caller. A failed database update—or a process stop between the sysfs write and database update—leaves saved state inconsistent with the device; startup replays that saved state and can lose a disable or re-disable an enabled device.

Make persistence failures visible and add recovery or reconciliation so saved authorization state is brought back in sync with sysfs.

Also at `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:372`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

// A composite USB device may expose keyboard, mouse and control interfaces.
// Keep their authorization state consistent with the selected physical device.
if (!UsbAuthorizationUtils::setInterfacesAuthorized(path, enable_device))
if (UsbAuthorizationUtils::setInterfacesAuthorized(path, enable_device)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · USB interfaces become inconsistent

When a USB path is identified but setInterfacesAuthorized() returns false because an interface read or write fails while the selected path remains writable, authorizedEnable() treats that failure as a non-USB case and writes only the selected path and its parent, then updates the database and reports success; sibling interfaces remain in a different authorization state.

Distinguish unsupported non-USB paths from USB operation failures and do not run the single-path fallback for the latter.

Also at deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:342-344.

Prompt for AI agents
In `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp` at line 333:

**USB interfaces become inconsistent**

When a USB path is identified but `setInterfacesAuthorized()` returns false because an interface read or write fails while the selected path remains writable, `authorizedEnable()` treats that failure as a non-USB case and writes only the selected path and its parent, then updates the database and reports success; sibling interfaces remain in a different authorization state.

Distinguish unsupported non-USB paths from USB operation failures and do not run the single-path fallback for the latter.

Also at `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:342-344`.

return false;
}
if (enable_device) {
file.write("1");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Failed sysfs writes report success

When a fallback sysfs authorized file opens but a write fails or writes fewer bytes than requested, authorizedEnable() ignores QFile::write() results, then updates the database and returns true; the caller sees success even though the requested authorization change was not made.

Check every sysfs write result and stop before updating the database or returning success when a write fails or is short.

Also at deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:360, deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:365-366, deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:370.

Prompt for AI agents
In `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp` at line 352:

**Failed sysfs writes report success**

When a fallback sysfs `authorized` file opens but a write fails or writes fewer bytes than requested, `authorizedEnable()` ignores `QFile::write()` results, then updates the database and returns true; the caller sees success even though the requested authorization change was not made.

Check every sysfs write result and stop before updating the database or returning success when a write fails or is short.

Also at `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:360`, `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:365-366`, `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:370`.

return false;
}
if (enable_device) {
file.write("1");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Failed parent open leaves partial state

When the fallback writes the target authorized file and a subsequent parent authorized file open fails, authorizedEnable() returns false without undoing the sysfs write; on a later parent-open failure, the parent may already have been changed. The caller sees failure while sysfs and the saved state are inconsistent.

Roll back any target and parent sysfs changes, and keep the database consistent, before returning failure.

Also at deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:355-359, deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:363-364.

Prompt for AI agents
In `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp` at line 352:

**Failed parent open leaves partial state**

When the fallback writes the target `authorized` file and a subsequent parent `authorized` file open fails, `authorizedEnable()` returns false without undoing the sysfs write; on a later parent-open failure, the parent may already have been changed. The caller sees failure while sysfs and the saved state are inconsistent.

Roll back any target and parent sysfs changes, and keep the database consistent, before returning failure.

Also at `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:355-359`, `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:363-364`.

} else {
file.write("0");
file.close();
EnableSqlManager::getInstance()->insertDataToAuthorizedTable(hclass, name, path, unique_id, true, strDriver);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Disabled non-USB devices return enabled

When a non-USB device is disabled through the fallback and the system restarts, EnableUtils::disableOutDevice() uses the USB-specific setInterfacesAuthorized() path, and startup restoration does not process these non-USB devices; their persisted disabled rows are skipped and the devices return enabled.

Include non-USB fallback devices in startup restoration and apply their persisted authorization state.

Prompt for AI agents
In `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp` at line 372:

**Disabled non-USB devices return enabled**

When a non-USB device is disabled through the fallback and the system restarts, `EnableUtils::disableOutDevice()` uses the USB-specific `setInterfacesAuthorized()` path, and startup restoration does not process these non-USB devices; their persisted disabled rows are skipped and the devices return enabled.

Include non-USB fallback devices in startup restoration and apply their persisted authorization state.

fpop.write("1");
fpop.close();

EnableSqlManager::getInstance()->removeDataFromAuthorizedTable(unique_id);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Sysfs and saved state diverge

When a database update fails or the process stops after changing sysfs but before updating the database, the sysfs change and database update are separate, and the database helpers do not report write failures to this caller. A failed database update—or a process stop between the sysfs write and database update—leaves saved state inconsistent with the device; startup replays that saved state and can lose a disable or re-disable an enabled device.

Make persistence failures visible and add recovery or reconciliation so saved authorization state is brought back in sync with sysfs.

Also at deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:372.

Prompt for AI agents
In `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp` at line 368:

**Sysfs and saved state diverge**

When a database update fails or the process stops after changing sysfs but before updating the database, the sysfs change and database update are separate, and the database helpers do not report write failures to this caller. A failed database update—or a process stop between the sysfs write and database update—leaves saved state inconsistent with the device; startup replays that saved state and can lose a disable or re-disable an enabled device.

Make persistence failures visible and add recovery or reconciliation so saved authorization state is brought back in sync with sysfs.

Also at `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:372`.

1. Root cause: isSafeSysfsPath() used QFileInfo::canonicalFilePath()
   to validate sysfs paths, which returns empty string when the path
   does not exist, causing the function to return false for removed
   PCI devices and blocking the enable flow
2. Fix: replace canonicalFilePath() with QDir::cleanPath() which is
   a pure string operation that does not require path existence,
   preserving path traversal protection via the existing ".." check
   and /sys/ prefix check after cleanPath
3. Impact: all 5 callers benefit (removeEnable, authorizedEnable,
   disableOutDevice, disableInDevice, unit tests); no behavior change
   for existing paths, security protection maintained

Log: fix sysfs path validation failing for non-existent device paths after disable

Influence:
1. Test disabling and re-enabling a PCI audio adapter
2. Test disabling and enabling USB devices via authorized path
3. Verify path traversal attempts with ".." are still rejected

fix: 修复禁用音频适配器后启用失败的问题

1. 根因:isSafeSysfsPath() 使用 canonicalFilePath() 校验 sysfs 路径,
   该函数在路径不存在时返回空字符串,导致设备禁用后路径消失时
   安全检查返回 false,阻断了启用流程
2. 方案:将 canonicalFilePath() 替换为 QDir::cleanPath(),纯字符串
   操作不要求路径存在,通过已有的 ".." 检查和 cleanPath 后的
   /sys/ 前缀检查保持路径穿越防护
3. 影响:5个调用方均受益(removeEnable、authorizedEnable、
   disableOutDevice、disableInDevice、单测),已有路径行为不变,
   安全防护不降级

Log: 修复禁用音频适配器后启用失败的问题

Influence:
1. 测试禁用PCI音频适配器后重新启用
2. 测试USB设备通过authorized路径禁用和启用
3. 验证包含".."的路径穿越攻击仍被拦截

PMS: BUG-374231
@github-actions

Copy link
Copy Markdown

TAG Bot

TAG: 6.0.76
EXISTED: no
DISTRIBUTION: unstable

@github-actions

Copy link
Copy Markdown
  • 检测到敏感词dmidecode, lshw变动
详情
    {
    "dmidecode": {
        "debian/changelog": [
            "  * fix(cpu): Fix CPU vendor info from dmidecode",
            "  * fix(cpu): Fix CPU vendor info from dmidecode",
            "  * fix: from dmidecode get cpu num error"
        ],
        "debian/control": [
            " dmidecode,"
        ],
        "debian/control.1": [
            " dmidecode,"
        ]
    },
    "lshw": {
        "debian/control": [
            " lshw,"
        ],
        "debian/control.1": [
            " lshw,"
        ]
    }
}
  • 检测到敏感词export变动
详情
    {
    "export": {
        "debian/changelog": {
            "b": [
                "  * fix(export): align table header and content in exported TXT file."
            ]
        },
        "debian/control.1": {
            "b": [
                " through which users can view parameters and export data of all hardware devices running in the system."
            ]
        },
        "debian/rules": {
            "a": [
                "export QT_SELECT := 5"
            ],
            "b": [
                "export QT_SELECT := 6",
                "export DH_VERBOSE=1"
            ]
        }
    }
}

@pengfeixx
pengfeixx changed the base branch from develop/eagle to master November 16, 2026 15:12
@pengfeixx pengfeixx changed the title fix: fallback to sysfs for non-USB device enable fix: use cleanPath instead of canonicalFilePath for sysfs check Nov 16, 2026
@deepin-bot

deepin-bot Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

TAG Bot

New tag: 6.0.77
DISTRIBUTION: unstable
Suggest: synchronizing this PR through rebase #990

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants