Skip to content

Conversation

@wangrong1069
Copy link
Contributor

@wangrong1069 wangrong1069 commented Nov 7, 2025

  • Security:

    • Updated _FORTIFY_SOURCE to version 2 in CMakeLists.txt files for enhanced buffer overflow detection.
    • Added User=root to deepin-devicecontrol.service for appropriate privilege execution.
    • Refactored D-Bus authorization checks in controlinterface.cpp and main.cpp to use SystemBusNameSubject for more robust service-level authentication.
    • Integrated authorization checks into deviceinterface.cpp methods (getInfo, refreshInfo, setMonitorDeviceFlag) and controlinterface.cpp methods to ensure privileged operations are properly authorized.
  • Dependency Management:

    • Updated debian/control to change the package section from devel to utils.
    • Added new dependencies (usbutils, pciutils, smartmontools, bluez, apt, lastore-daemon, kmod, iputils-ping, net-tools) to debian/control to support new functionalities.
  • Build System & Code Refactoring:

    • Modified DriverInstallerApt::executeCommand to accept QStringList arguments, improving command execution flexibility.
    • Replaced temporary path handling in DriverBackupThread.cpp with QTemporaryDir for safer and more reliable temporary directory management.
    • Removed deprecated D-Bus service files (com.deepin.Devicemanager.service, com.deepin.Devicemanager.xml) and related build configurations.
    • Updated .gitignore and rpm/deepin-devicemanager.spec to reflect build artifact changes and D-Bus service removal.

Summary by Sourcery

Strengthen service security and refactor build and dependency management across the project

Enhancements:

  • Replace UnixProcessSubject with SystemBusNameSubject and add authorization checks to control and device interfaces and main entrypoint
  • Extend DriverInstallerApt.executeCommand to accept argument lists and remove bash wrappers
  • Switch to QTemporaryDir for driver backup to use secure temporary paths

Build:

  • Upgrade _FORTIFY_SOURCE to 2 in all CMakeLists and test builds for enhanced buffer overflow protection
  • Remove deprecated D-Bus service files and update service installation rules in CMake, RPM spec, and .gitignore

Deployment:

  • Add User=root to deepin-devicecontrol.service for proper privilege execution

Chores:

  • Update debian/control package section to utils and add usbutils, pciutils, smartmontools, bluez, apt, lastore-daemon, kmod, iputils-ping, and net-tools dependencies

- Security:
    - Updated _FORTIFY_SOURCE to version 2 in CMakeLists.txt files for enhanced buffer overflow detection.
    - Added User=root to deepin-devicecontrol.service for appropriate privilege execution.
    - Refactored D-Bus authorization checks in controlinterface.cpp and main.cpp to use SystemBusNameSubject for more robust service-level authentication.
    - Integrated authorization checks into deviceinterface.cpp methods (getInfo, refreshInfo, setMonitorDeviceFlag) and controlinterface.cpp methods to ensure privileged operations are properly authorized.

- Dependency Management:
    - Updated debian/control to change the package section from devel to utils.
    - Added new dependencies (usbutils, pciutils, smartmontools, bluez, apt, lastore-daemon, kmod, iputils-ping, net-tools) to debian/control to support new functionalities.

- Build System & Code Refactoring:
    - Modified DriverInstallerApt::executeCommand to accept QStringList arguments, improving command execution flexibility.
    - Replaced temporary path handling in DriverBackupThread.cpp with QTemporaryDir for safer and more reliable temporary directory management.
    - Removed deprecated D-Bus service files (com.deepin.Devicemanager.service, com.deepin.Devicemanager.xml) and related build configurations.
    - Updated .gitignore and rpm/deepin-devicemanager.spec to reflect build artifact changes and D-Bus service removal.
@deepin-ci-robot
Copy link

deepin pr auto review

我来对这次代码变更进行审查:

  1. 安全性改进:
  • 将所有CMakeLists.txt中的D_FORTITY_SOURCE=1升级为D_FORTIFY_SOURCE=2,这提供了更强的缓冲区溢出保护
  • 在deepin-devicecontrol.service中增加了User=root,确保服务以root权限运行
  • 在多个关键函数中增加了权限检查getUserAuthorPasswd(),包括getInfo、refreshInfo、setMonitorDeviceFlag等
  • 优化了权限验证机制,从UnixProcessSubject改为SystemBusNameSubject,使用更安全的DBus服务名验证
  1. 代码质量改进:
  • 删除了不必要的DBus服务文件(com.deepin.Devicemanager.service和.xml)
  • 优化了命令执行方式,从通过bash执行改为直接调用命令,减少了安全风险
  • 使用QTemporaryDir替代固定的临时目录路径,提高了安全性
  • 改进了依赖项列表格式,使其更易读
  1. 性能优化:
  • 优化了命令执行方式,减少了中间shell调用
  • 使用更高效的权限验证机制
  1. 建议改进:
  • 建议在DriverInstallerApt类中为executeCommand添加超时机制,防止命令执行卡死
  • 建议在权限验证失败时记录更详细的错误信息,便于调试
  • 建议对QTemporaryDir的使用添加错误处理
  • 建议在systemd服务文件中添加更多的安全限制,如PrivateTmp=true等
  1. 其他建议:
  • 建议在debian/control中添加更详细的包描述
  • 建议为新增的依赖项(如usbutils, pciutils等)添加版本要求
  • 建议在CMakeLists.txt中添加更详细的编译选项说明

总体来说,这次变更主要提升了系统的安全性和代码质量,是一个积极的改进。建议在后续版本中考虑上述改进建议。

@sourcery-ai
Copy link

sourcery-ai bot commented Nov 7, 2025

Reviewer's Guide

This PR hardens service safety by upgrading compile-time fortify settings, refactoring D-Bus authorization to use SystemBusNameSubject, injecting authorization guards into control and device interfaces, enhancing command execution flexibility and temporary path management, and cleaning up deprecated service artifacts and packaging dependencies.

Sequence diagram for refactored D-Bus authorization using SystemBusNameSubject

sequenceDiagram
    participant Client
    participant "D-Bus Service"
    participant Authority

    Client->>"D-Bus Service": Request privileged operation
    "D-Bus Service"->>Authority: checkAuthorizationSync("com.deepin.deepin-devicemanager.checkAuthentication" SystemBusNameSubject(service()) AllowUserInteraction)
    Authority-->>"D-Bus Service": Authorization result
    alt Authorized
        "D-Bus Service"-->>Client: Perform operation
    else Not authorized
        "D-Bus Service"-->>Client: Deny operation
    end
Loading

Entity relationship diagram for updated debian/control dependencies

erDiagram
    PACKAGE ||--o{ DEPENDENCY : includes
    PACKAGE {
        string name
        string section
    }
    DEPENDENCY {
        string name
    }
    PACKAGE ||--o{ usbutils : "usbutils"
    PACKAGE ||--o{ pciutils : "pciutils"
    PACKAGE ||--o{ smartmontools : "smartmontools"
    PACKAGE ||--o{ bluez : "bluez"
    PACKAGE ||--o{ apt : "apt"
    PACKAGE ||--o{ lastore-daemon : "lastore-daemon"
    PACKAGE ||--o{ kmod : "kmod"
    PACKAGE ||--o{ iputils-ping : "iputils-ping"
    PACKAGE ||--o{ net-tools : "net-tools"
Loading

Class diagram for updated DriverInstallerApt command execution

classDiagram
    class DriverInstallerApt {
        +void aptClean()
        +QString executeCommand(const QString &cmd, const QStringList &args)
        +void doOperate(const QString &package, const QString &version)
        -QProcess *m_process
    }

    DriverInstallerApt : executeCommand(const QString &cmd, const QStringList &args)
Loading

Class diagram for authorization guards in DeviceInterface and ControlInterface

classDiagram
    class DeviceInterface {
        +QString getInfo(const QString &key)
        +void refreshInfo()
        +void setMonitorDeviceFlag(bool flag)
        -bool getUserAuthorPasswd()
    }
    class ControlInterface {
        +QString getRemoveInfo()
        +QString getAuthorizedInfo()
        +bool isDeviceEnabled(const QString &unique_id)
        +int isNetworkWakeup(const QString &logicalName)
        +bool monitorWorkingDBFlag()
        +QStringList checkModuleInUsed(const QString &modulename)
        +bool isBlackListed(const QString &modName)
        +bool isArchMatched(const QString &filePath)
        +bool isDebValid(const QString &filePath)
        -bool getUserAuthorPasswd()
    }

    DeviceInterface : getUserAuthorPasswd()
    ControlInterface : getUserAuthorPasswd()
Loading

Class diagram for updated DriverBackupThread temporary directory management

classDiagram
    class DriverBackupThread {
        +void run()
    }
    class QTemporaryDir {
        +QString path()
    }
    DriverBackupThread --> QTemporaryDir : uses
Loading

File-Level Changes

Change Details Files
Upgrade buffer overflow protection flag to -D_FORTIFY_SOURCE=2 across CMake configurations
  • Replaced Fortify source version in root project CMakeLists
  • Applied same update in devicecontrol CMakeLists
  • Updated fortify flag in deviceinfo CMakeLists
  • Adjusted fortify flag in test CMakeLists
deepin-devicemanager/CMakeLists.txt
deepin-devicemanager-server/deepin-devicecontrol/CMakeLists.txt
deepin-devicemanager-server/deepin-deviceinfo/CMakeLists.txt
deepin-devicemanager-server/tests/CMakeLists.txt
deepin-devicemanager/tests/CMakeLists.txt
Refactor D-Bus authorization checks to use SystemBusNameSubject
  • Replaced pid-based UnixProcessSubject checks in controlinterface
  • Switched to SystemBusNameSubject for service authentication in main
deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp
deepin-devicemanager/src/main.cpp
Enforce authorization precondition in service interface methods
  • Added getUserAuthorPasswd gating to all controlinterface operations
  • Integrated auth guard into deviceinterface methods (getInfo, refreshInfo, setMonitorDeviceFlag)
deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp
deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/deviceinterface.cpp
Extend DriverInstallerApt to support argument lists
  • Changed executeCommand signature to accept QStringList args
  • Updated callers to pass command and argument lists
  • Replaced bash -c invocations with direct process starts
deepin-devicemanager-server/deepin-devicecontrol/src/drivercontrol/driverinstallerapt.cpp
deepin-devicemanager-server/deepin-devicecontrol/src/drivercontrol/driverinstallerapt.h
Switch to QTemporaryDir for safe temporary path management
  • Removed hard-coded temp path macro
  • Introduced QTemporaryDir for backup directory creation
deepin-devicemanager/src/DriverControl/DriverBackupThread.cpp
Remove deprecated D-Bus service definitions and adjust artifact tracking
  • Deleted old .service and .xml D-Bus files
  • Removed their installation from CMake and RPM spec
  • Added User=root to deepin-devicecontrol.service unit
  • Updated .gitignore to reflect artifact removal
deepin-devicecontrol.service
deepin-devicemanager/assets/dbus/com.deepin.Devicemanager.service
deepin-devicemanager/assets/dbus/com.deepin.Devicemanager.xml
.gitignore
rpm/deepin-devicemanager.spec
deepin-devicemanager/CMakeLists.txt
Update Debian package section and add new runtime dependencies
  • Changed package section from devel to utils
  • Added usbutils, pciutils, smartmontools, bluez, apt, lastore-daemon, kmod, iputils-ping and net-tools dependencies
debian/control

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

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes - here's some feedback:

  • The repeated getUserAuthorPasswd checks could be extracted into a common guard or macro to reduce duplication and ensure consistency across methods.
  • In DriverInstallerApt, consider checking QProcess exit status and capturing stderr to properly detect and handle command failures instead of only reading stdout.
  • Review the QTemporaryDir usage in DriverBackupThread—its template argument, scope, and lifetime—to ensure the temp directory isn’t removed prematurely and is created safely.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The repeated getUserAuthorPasswd checks could be extracted into a common guard or macro to reduce duplication and ensure consistency across methods.
- In DriverInstallerApt, consider checking QProcess exit status and capturing stderr to properly detect and handle command failures instead of only reading stdout.
- Review the QTemporaryDir usage in DriverBackupThread—its template argument, scope, and lifetime—to ensure the temp directory isn’t removed prematurely and is created safely.

## Individual Comments

### Comment 1
<location> `deepin-devicemanager-server/deepin-devicecontrol/src/drivercontrol/driverinstallerapt.cpp:84` </location>
<code_context>
+    qCDebug(appLog) << "Executing command:" << cmd << args;

     QProcess process;
-    process.start("bash", QStringList() << "-c" << cmd);
+    process.start(cmd, args);
     process.waitForFinished();
     return QString::fromUtf8(process.readAllStandardOutput());
</code_context>

<issue_to_address>
**suggestion:** Directly starting commands without a shell may affect environment and command parsing.

Confirm that all commands and arguments used are compatible with direct invocation, as shell-specific features will no longer be available.

Suggested implementation:

```cpp
/*
 * Note: This function now directly invokes the command without a shell.
 * Ensure that 'cmd' and 'args' do not use shell-specific features (pipes, redirection, globbing, etc).
 * If shell features are needed, use: process.start("bash", QStringList() << "-c" << fullCommandString);
 */
QString DriverInstallerApt::executeCommand(const QString &cmd, const QStringList &args)
{
    qCDebug(appLog) << "Executing command:" << cmd << args;

    // Check for shell-specific features in cmd or args before invoking
    // (This is a manual process: audit all calls to executeCommand in this file and others)
    QProcess process;
    process.start(cmd, args);
    process.waitForFinished();
    return QString::fromUtf8(process.readAllStandardOutput());
}

```

You must audit all calls to `executeCommand` throughout the codebase. If any call passes a command or arguments that use shell features (e.g., `"ls | grep foo"`, `"echo $PATH"`, `"*.deb"`), you must refactor those calls to either:
- Avoid shell features and use only direct command/argument invocation, or
- Use the shell explicitly: `process.start("bash", QStringList() << "-c" << fullCommandString);`

For example, if you previously had:
`executeCommand("bash", QStringList() << "-c" << "ls | grep foo");`
You should keep this as-is if shell features are required.

If you had:
`executeCommand("apt", QStringList() << "update");`
This is safe, as it does not use shell features.

Document this requirement for future maintainers.
</issue_to_address>

### Comment 2
<location> `deepin-devicemanager-server/deepin-deviceinfo/src/loadinfo/deviceinterface.cpp:47-50` </location>
<code_context>
     qCDebug(appLog) << "Getting info for key:" << key;
+
+    // 获取设备信息需要身份验证
+    if (!getUserAuthorPasswd()) {
+        qCWarning(appLog) << "Authorization failed for getInfo operation";
+        return "0";
+    }
+
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Returning "0" on authorization failure may be ambiguous.

Use an empty string or a distinct error value to clearly indicate authorization failure, avoiding confusion with valid '0' results.

```suggestion
    if (!getUserAuthorPasswd()) {
        qCWarning(appLog) << "Authorization failed for getInfo operation";
        return "";
    }
```
</issue_to_address>

### Comment 3
<location> `deepin-devicemanager/src/DriverControl/DriverBackupThread.cpp:38-39` </location>
<code_context>
         }

-        QString backupPath =  QString("%1/driver/%2").arg(DB_PATH_TMP).arg(debname);
+        QTemporaryDir tempDir(QDir::tempPath() + "/XXXXXX");
+        QString backupPath =  QString("%1/driver/%2").arg(tempDir.path()).arg(debname);
         QDir destdir(backupPath);
         if (!destdir.exists()) {
</code_context>

<issue_to_address>
**issue (bug_risk):** Using QTemporaryDir may result in backup data being deleted prematurely.

If backupPath is required after the thread completes, QTemporaryDir will remove the directory, risking data loss. Use a persistent directory or ensure QTemporaryDir's lifetime covers all necessary operations.
</issue_to_address>

### Comment 4
<location> `deepin-devicemanager/src/main.cpp:108` </location>
<code_context>
         qCDebug(appLog) << "PageDriverControl::installDriverLogical at name page";
-        // 驱动安装之前需要先提权
-        Authority::Result result = Authority::instance()->checkAuthorizationSync("com.deepin.deepin-devicemanager.checkAuthentication",
-                                                                                 UnixProcessSubject(getpid()),
-                                                                                 Authority::AllowUserInteraction);
-        if (result != Authority::Yes) {
</code_context>

<issue_to_address>
**🚨 question (security):** Changing authorization subject may affect which user is authorized.

Confirm that using SystemBusNameSubject aligns with your security requirements, particularly in multi-user or service scenarios.
</issue_to_address>

### Comment 5
<location> `deepin-devicemanager-server/deepin-devicecontrol/src/controlinterface.cpp:130` </location>
<code_context>

 QString ControlInterface::getRemoveInfo()
 {
+    if (!getUserAuthorPasswd())
+        return {};
     return EnableSqlManager::getInstance()->removedInfo();
</code_context>

<issue_to_address>
**issue (complexity):** Consider using macros or inline helpers to centralize the authorization guard logic and reduce repetitive code in each method.

Consider centralizing the guard into a couple of very small macros (or inline helpers) so each method only needs one line, e.g.:

```cpp
// In ControlInterface.cpp, near the top:
#define AUTH_GUARD_RET(val) \
    do { if (!getUserAuthorPasswd()) return (val); } while(0)
#define AUTH_GUARD() AUTH_GUARD_RET(/*void*/)
```

Then each method becomes:

```cpp
QString ControlInterface::getRemoveInfo()
{
    AUTH_GUARD_RET({});                    // was: if (!getUserAuthorPasswd()) return {};
    return EnableSqlManager::getInstance()->removedInfo();
}

void ControlInterface::disableOutDevice(const QString &devInfo)
{
    AUTH_GUARD();                          // was: if (!getUserAuthorPasswd()) return;
    EnableUtils::disableOutDevice(devInfo);
}

bool ControlInterface::enable(const QString &hclass, …)
{
    AUTH_GUARD_RET(false);                 // was: if (!getUserAuthorPasswd()) return {};

}
```

That removes the repetitive boilerplate while preserving exactly the same behavior.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@deepin-ci-robot
Copy link

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: lzwind, wangrong1069

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

@wangrong1069
Copy link
Contributor Author

/merge

@deepin-bot deepin-bot bot merged commit 6ed3d56 into linuxdeepin:master Nov 10, 2025
18 checks passed
@wangrong1069 wangrong1069 deleted the pr1107 branch November 10, 2025 01:59
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.

3 participants