understanding-tauri-lifecycle-security

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Tauri Application Lifecycle Security

Tauri 应用生命周期安全

Security in Tauri applications depends on systematic protection across all lifecycle stages. The weakest link in your application lifecycle essentially defines your security posture.
Tauri 应用的安全依赖于对所有生命周期阶段的系统性防护。应用生命周期中的最薄弱环节本质上决定了你的安全态势。

Core Security Principle

核心安全原则

Tauri implements a two-tier security model:
  • Rust Core: Full system access
  • WebView Frontend: Access only through controlled IPC layer
Any code executed in the WebView has only access to exposed system resources via the well-defined IPC layer.

Tauri 实现了双层安全模型:
  • Rust Core:拥有完整的系统访问权限
  • WebView Frontend:仅能通过受控的IPC层访问系统资源
WebView中执行的任何代码仅能通过定义完善的IPC层访问暴露的系统资源。

Development Phase Threats

开发阶段威胁

Upstream Dependency Risks

上游依赖风险

Third-party dependencies may lack the strict oversight that Tauri maintains.
Mitigation Strategies:
bash
undefined
第三方依赖可能缺乏Tauri所保持的严格监管。
缓解策略:
bash
undefined

Scan Rust dependencies for vulnerabilities

扫描Rust依赖中的漏洞

cargo audit
cargo audit

Scan npm dependencies

扫描npm依赖

npm audit
npm audit

Advanced supply chain analysis

高级供应链分析

cargo vet cargo crev cargo supply-chain

**Best Practices:**
- Keep Tauri, `rustc`, and `nodejs` current to patch vulnerabilities
- Evaluate trustworthiness of third-party libraries before integration
- Prefer consuming critical dependencies via git hash revisions rather than version ranges

```toml
cargo vet cargo crev cargo supply-chain

**最佳实践:**
- 保持Tauri、`rustc`和`nodejs`为最新版本以修复漏洞
- 在集成前评估第三方库的可信度
- 优先通过Git哈希修订版本而非版本范围引入关键依赖

```toml

Cargo.toml - Pin to specific commit hash

Cargo.toml - 固定到特定提交哈希

[dependencies] critical-lib = { git = "https://github.com/org/critical-lib", rev = "abc123def456" }
undefined
[dependencies] critical-lib = { git = "https://github.com/org/critical-lib", rev = "abc123def456" }
undefined

Development Server Exposure

开发服务器暴露

Development servers typically run unencrypted and unauthenticated on local networks, allowing attackers to push malicious frontend code to development devices.
Threat Scenario:
Attacker on same network -> Intercepts dev server traffic -> Injects malicious frontend code
Mitigation:
  • Develop only on trusted networks
  • Implement mutual TLS (mTLS) authentication when necessary
  • Note: Tauri's built-in dev server lacks mutual authentication features
开发服务器通常在本地网络中以未加密、未认证的方式运行,攻击者可借此向开发设备推送恶意前端代码。
威胁场景:
同一网络中的攻击者 -> 拦截开发服务器流量 -> 注入恶意前端代码
缓解措施:
  • 仅在可信网络中进行开发
  • 必要时实现双向TLS(mTLS)认证
  • 注意:Tauri内置的开发服务器不具备双向认证功能

Machine Hardening

机器加固

PracticePurpose
Avoid admin accounts for codingLimit blast radius of compromise
Block secrets from version controlPrevent credential leaks
Use hardware security tokensMinimize compromise impact
Minimize installed applicationsReduce attack surface
实践目的
避免使用管理员账号编码限制被攻陷后的影响范围
阻止密钥进入版本控制防止凭证泄露
使用硬件安全令牌最小化被攻陷的影响
最小化已安装应用数量减少攻击面

Source Control Security

源代码控制安全

Required Protections:
  • Implement proper access controls in version control systems
  • Require contributor commit signing to prevent unauthorized attribution
  • Use established hardening guidelines for authentication workflows
bash
undefined
必要防护措施:
  • 在版本控制系统中实施适当的访问控制
  • 要求贡献者对提交进行签名,防止未经授权的归属
  • 为认证工作流采用已确立的加固指南
bash
undefined

Enable commit signing

启用提交签名

git config --global commit.gpgsign true git config --global user.signingkey YOUR_KEY_ID

---
git config --global commit.gpgsign true git config --global user.signingkey YOUR_KEY_ID

---

Build Phase Threats

构建阶段威胁

Build System Trust

构建系统信任

CI/CD systems access source code, secrets, and can modify builds without local verification.
Threat Vectors:
  1. Compromised CI/CD provider
  2. Malicious build scripts
  3. Unauthorized secret access
  4. Build artifact tampering
Mitigation Options:
  • Trust reputable third-party providers (GitHub Actions, GitLab CI)
  • Host and control your own infrastructure for sensitive applications
CI/CD系统可访问源代码、密钥,且能在无需本地验证的情况下修改构建产物。
威胁向量:
  1. 被攻陷的CI/CD提供商
  2. 恶意构建脚本
  3. 未经授权的密钥访问
  4. 构建产物篡改
缓解选项:
  • 信任知名第三方提供商(GitHub Actions、GitLab CI)
  • 对于敏感应用,自行托管并控制基础设施

Binary Signing

二进制签名

Applications must be cryptographically signed for their target platform.
Platform Requirements:
PlatformSigning Requirement
macOSApple Developer Certificate + Notarization
WindowsCode Signing Certificate (EV recommended)
LinuxGPG signing for packages
Key Protection:
bash
undefined
应用必须针对其目标平台进行加密签名。
平台要求:
平台签名要求
macOSApple开发者证书 + 公证
Windows代码签名证书(推荐EV证书)
Linux软件包GPG签名
密钥保护:
bash
undefined

Use hardware tokens for signing credentials

使用硬件令牌存储签名凭证

Prevents compromised build systems from leaking keys

防止被攻陷的构建系统泄露密钥

Example: Using YubiKey for code signing

示例:使用YubiKey进行代码签名

pkcs11-tool --module /usr/lib/opensc-pkcs11.so --sign

Hardware tokens prevent key exfiltration but cannot prevent key misuse on a compromised system.
pkcs11-tool --module /usr/lib/opensc-pkcs11.so --sign

硬件令牌可防止密钥泄露,但无法阻止在被攻陷系统上的密钥滥用。

Reproducible Builds Challenge

可复现构建挑战

Rust is not fully reliable at producing reproducible builds despite theoretical support. Frontend bundlers similarly struggle with reproducible output.
Implications:
  • Cannot entirely eliminate reliance on build system trust
  • Implement multiple verification layers
  • Consider build provenance attestation

尽管理论上支持,但Rust在生成可复现构建方面并非完全可靠。前端打包工具同样难以生成可复现的输出。
影响:
  • 无法完全消除对构建系统的信任依赖
  • 实现多层验证机制
  • 考虑构建来源证明

Distribution Threats

分发阶段威胁

Loss of control over manifest servers, build servers, or binary hosting creates critical vulnerability points.
失去对清单服务器、构建服务器或二进制文件托管的控制会造成关键漏洞点。

Attack Vectors

攻击向量

Manifest Server Compromise -> Malicious update metadata -> Users download tampered binaries
Build Server Compromise -> Injected malware at build time -> Signed malicious releases
Binary Host Compromise -> Replaced binaries -> Users download malicious versions
清单服务器被攻陷 -> 恶意更新元数据 -> 用户下载篡改后的二进制文件
构建服务器被攻陷 -> 构建时注入恶意软件 -> 签名后的恶意版本发布
二进制文件托管被攻陷 -> 替换二进制文件 -> 用户下载恶意版本

Mitigation Strategies

缓解策略

  1. Secure Update Channels
    • Use HTTPS for all update communications
    • Implement certificate pinning where possible
    • Verify update signatures client-side
  2. Binary Integrity
    • Publish checksums alongside releases
    • Use signed manifests for updates
    • Consider transparency logs
  3. Infrastructure Security
    • Multi-factor authentication for all distribution systems
    • Audit logging for binary access
    • Separate credentials for different environments

  1. 安全更新渠道
    • 所有更新通信使用HTTPS
    • 尽可能实现证书固定
    • 在客户端验证更新签名
  2. 二进制完整性
    • 随发布版本一起发布校验和
    • 对更新使用签名清单
    • 考虑使用透明日志
  3. 基础设施安全
    • 所有分发系统启用多因素认证
    • 对二进制文件访问进行审计日志记录
    • 为不同环境使用独立凭证

Runtime Threats

运行阶段威胁

WebView Security Model

WebView安全模型

Tauri assumes webview components are inherently insecure and implements multiple protection layers.
Defense Layers:
                    +------------------+
                    |   Untrusted      |
                    |   Frontend Code  |
                    +--------+---------+
                             |
                    +--------v---------+
                    |       CSP        |  <- Restricts communication types
                    +--------+---------+
                             |
                    +--------v---------+
                    |   Capabilities   |  <- Controls API access
                    +--------+---------+
                             |
                    +--------v---------+
                    |   Permissions    |  <- Fine-grained command control
                    +--------+---------+
                             |
                    +--------v---------+
                    |      Scopes      |  <- Resource-level restrictions
                    +--------+---------+
                             |
                    +--------v---------+
                    |   Rust Backend   |  <- Trusted system access
                    +------------------+
Tauri认为WebView组件本质上是不安全的,因此实现了多层防护机制。
防御层级:
                    +------------------+
                    |   不可信         |
                    |   前端代码       |
                    +--------+---------+
                             |
                    +--------v---------+
                    |       CSP        |  <- 限制通信类型
                    +--------+---------+
                             |
                    +--------v---------+
                    |   能力配置       |  <- 控制API访问
                    +--------+---------+
                             |
                    +--------v---------+
                    |   权限控制       |  <- 细粒度命令控制
                    +--------+---------+
                             |
                    +--------v---------+
                    |   范围限制       |  <- 资源级别的访问限制
                    +--------+---------+
                             |
                    +--------v---------+
                    |   Rust后端       |  <- 可信的系统访问
                    +------------------+

Content Security Policy (CSP)

内容安全策略(CSP)

CSP restricts webview communication types to prevent XSS and injection attacks.
Configuration in
tauri.conf.json
:
json
{
  "app": {
    "security": {
      "csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'"
    }
  }
}
CSP Best Practices:
  • Start with restrictive policy, relax only as needed
  • Avoid
    'unsafe-eval'
    and
    'unsafe-inline'
    for scripts
  • Use nonces or hashes for inline scripts when required
CSP限制WebView的通信类型,以防止XSS和注入攻击。
tauri.conf.json
中的配置:
json
{
  "app": {
    "security": {
      "csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'"
    }
  }
}
CSP最佳实践:
  • 从严格的策略开始,仅在需要时放宽
  • 避免为脚本使用
    'unsafe-eval'
    'unsafe-inline'
  • 必要时为内联脚本使用随机数或哈希

Capabilities Configuration

能力配置

Define which permissions are granted to specific windows.
Example:
src-tauri/capabilities/main.json
json
{
  "$schema": "../gen/schemas/desktop-schema.json",
  "identifier": "main-capability",
  "description": "Capability for the main window",
  "windows": ["main"],
  "permissions": [
    "core:path:default",
    "core:window:allow-set-title",
    "fs:read-files"
  ]
}
Security Notes:
  • Windows in multiple capabilities merge security boundaries
  • Security boundaries depend on window labels, not titles
  • Capabilities protect against frontend compromise and privilege escalation
定义为特定窗口授予的权限。
示例:
src-tauri/capabilities/main.json
json
{
  "$schema": "../gen/schemas/desktop-schema.json",
  "identifier": "main-capability",
  "description": "主窗口的能力配置",
  "windows": ["main"],
  "permissions": [
    "core:path:default",
    "core:window:allow-set-title",
    "fs:read-files"
  ]
}
安全注意事项:
  • 属于多个能力配置的窗口会合并安全边界
  • 安全边界依赖于窗口标签,而非标题
  • 能力配置可防止前端被攻陷后的权限提升

Permission Scopes

权限范围

Control resource access at a granular level.
Example: File System Scope
toml
undefined
细粒度控制资源访问。
示例:文件系统范围
toml
undefined

src-tauri/permissions/fs-restricted.toml

src-tauri/permissions/fs-restricted.toml

[[permission]] identifier = "fs-home-restricted" description = "Allow home directory access except secrets" commands.allow = ["read_file", "write_file"]
[[scope.allow]] path = "$HOME/*"
[[scope.deny]] path = "$HOME/.ssh/*"
[[scope.deny]] path = "$HOME/.gnupg/*"
[[scope.deny]] path = "$HOME/.aws/*"
undefined
[[permission]] identifier = "fs-home-restricted" description = "允许访问主目录,但排除密钥相关目录" commands.allow = ["read_file", "write_file"]
[[scope.allow]] path = "$HOME/*"
[[scope.deny]] path = "$HOME/.ssh/*"
[[scope.deny]] path = "$HOME/.gnupg/*"
[[scope.deny]] path = "$HOME/.aws/*"
undefined

Prototype Freezing

原型冻结

Prevent JavaScript prototype pollution attacks.
json
{
  "app": {
    "security": {
      "freezePrototype": true
    }
  }
}
防止JavaScript原型污染攻击。
json
{
  "app": {
    "security": {
      "freezePrototype": true
    }
  }
}

Remote API Access Control

远程API访问控制

Control which external URLs can access Tauri commands.
json
{
  "identifier": "remote-api-capability",
  "remote": {
    "urls": ["https://*.yourdomain.com"]
  },
  "permissions": ["limited-api-access"]
}

控制哪些外部URL可访问Tauri命令。
json
{
  "identifier": "remote-api-capability",
  "remote": {
    "urls": ["https://*.yourdomain.com"]
  },
  "permissions": ["limited-api-access"]
}

Threat Mitigation Quick Reference

威胁缓解速查

PhaseThreatMitigation
DevelopmentDependency vulnerabilities
cargo audit
,
npm audit
, pin versions
DevelopmentDev server exposureTrusted networks, mTLS
DevelopmentCredential leaksHardware tokens, gitignore secrets
BuildCI/CD compromiseTrusted providers, self-hosted options
BuildUnsigned binariesPlatform signing, hardware key storage
DistributionManifest tamperingHTTPS, certificate pinning
DistributionBinary replacementChecksums, signed manifests
RuntimeXSS/injectionCSP, input validation
RuntimePrivilege escalationCapabilities, permissions, scopes
RuntimePrototype pollution
freezePrototype: true

阶段威胁缓解措施
开发依赖漏洞
cargo audit
npm audit
、固定版本
开发开发服务器暴露可信网络、mTLS
开发凭证泄露硬件令牌、gitignore排除密钥
构建CI/CD被攻陷可信提供商、自托管选项
构建未签名二进制文件平台签名、硬件密钥存储
分发清单篡改HTTPS、证书固定
分发二进制文件替换校验和、签名清单
运行XSS/注入CSP、输入验证
运行权限提升能力配置、权限控制、范围限制
运行原型污染
freezePrototype: true

Security Configuration Template

安全配置模板

Minimal Secure Configuration:
json
{
  "app": {
    "security": {
      "csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'",
      "freezePrototype": true,
      "capabilities": ["main-capability"],
      "dangerousDisableAssetCspModification": false,
      "assetProtocol": {
        "enable": false,
        "scope": []
      }
    }
  }
}
Capability File Structure:
src-tauri/
├── capabilities/
│   ├── main.json          # Main window capabilities
│   └── settings.json      # Settings window capabilities
├── permissions/
│   └── custom-scope.toml  # Custom permission scopes
└── tauri.conf.json

最小安全配置:
json
{
  "app": {
    "security": {
      "csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'",
      "freezePrototype": true,
      "capabilities": ["main-capability"],
      "dangerousDisableAssetCspModification": false,
      "assetProtocol": {
        "enable": false,
        "scope": []
      }
    }
  }
}
能力配置文件结构:
src-tauri/
├── capabilities/
│   ├── main.json          # 主窗口能力配置
│   └── settings.json      # 设置窗口能力配置
├── permissions/
│   └── custom-scope.toml  # 自定义权限范围
└── tauri.conf.json

Vulnerability Reporting

漏洞上报

If you discover security vulnerabilities in Tauri applications:
  1. Use GitHub Vulnerability Disclosure on affected repositories
  2. Email: security@tauri.app
  3. Do not publicly discuss findings before coordinated resolution
  4. Limited bounty consideration available

如果你在Tauri应用中发现安全漏洞:
  1. 在受影响的仓库上使用GitHub漏洞披露功能
  2. 邮件:security@tauri.app
  3. 在协调解决前不要公开讨论发现的问题
  4. 可考虑提供有限的赏金

Key Takeaways

关键要点

  1. Defense in Depth: No single layer provides sufficient protection
  2. Least Privilege: Grant minimum necessary permissions
  3. Update Regularly: WebView patches reach users faster through OS updates
  4. Trust Boundaries: Frontend code is untrusted; validate everything in Rust
  5. Lifecycle Coverage: Security must span development through runtime
  1. 深度防御:单一防护层无法提供足够的保护
  2. 最小权限:仅授予必要的最小权限
  3. 定期更新:通过系统更新,WebView补丁可更快送达用户
  4. 信任边界:前端代码不可信;在Rust中验证所有内容
  5. 全生命周期覆盖:安全必须贯穿开发到运行的所有阶段