使用原生程式碼
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
OWASP 類別:MASVS-CODE:程式碼品質
總覽
Android 應用程式可利用以 C 和 C++ 等語言編寫的原生程式碼,實作特定功能。不過,當應用程式使用 Java Native Interface (JNI) 與此原生程式碼互動時,可能會暴露出緩衝區溢位和其他原生程式碼實作中可能出現的問題等漏洞。
影響
雖然效能最佳化和模糊處理等功能帶來非常正面的影響,但在 Android 應用程式中使用原生程式碼可能會對安全性造成負面影響。C/C++ 等原生程式碼語言缺乏 Java/Kotlin 的記憶體安全功能,因此容易發生緩衝區溢位、使用已釋放記憶體的錯誤和其他記憶體毀損問題等漏洞,導致應用程式當機或任意程式碼執行。此外,即使其他部分是使用 Java 安全編寫,原生程式碼元件仍可能存在安全漏洞,進而危害整個應用程式。
因應措施
開發和編寫程式碼指南
- 安全程式碼規範:針對 C/C++ 專案,請遵循已建立的安全程式碼標準 (例如CERT、OWASP) 來緩解安全漏洞,例如緩衝區溢位、整數溢位和格式字串攻擊。優先採用以品質和安全性聞名的 Abseil 等程式庫。盡可能採用 Rust 等記憶體安全語言,其效能可與 C/C++ 相提並論。
- 輸入驗證:嚴格驗證從外部來源接收的所有輸入資料,包括使用者輸入內容、網路資料和檔案,以防範注入攻擊和其他漏洞。
強化編譯選項
使用 ELF 格式的原生程式庫可透過啟用堆疊保護 (Canary)、可讀取重新配置 (RELRO)、資料執行防止 (NX) 和位置無關可執行檔 (PIE) 等保護機制,強化防範各種漏洞。方便起見,Android NDK 編譯選項已預設啟用所有這些保護措施。
如要驗證二進位檔中這些安全機制的實作方式,您可以使用 hardening-check
或 pwntools
等工具。
Bash
$ pwn checksec --file path/to/libnativecode.so
Arch: aarch64-64-little
RELRO: Full RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled
確認第三方程式庫沒有安全漏洞
選擇第三方程式庫時,請優先使用在開發社群中享有良好聲譽的程式庫。Google Play SDK 索引等資源可協助您找出備受好評且值得信賴的程式庫。務必將程式庫更新至最新版本,並使用 Exploit-DB 中的資料庫等資源主動搜尋任何相關的已知安全漏洞。使用 [library_name] vulnerability
或 [library_name] CVE
等關鍵字進行網路搜尋,可能會洩漏重要安全資訊。
資源
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-07-26 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-07-26 (世界標準時間)。"],[],[],null,["# Use of native code\n\n\u003cbr /\u003e\n\n**OWASP category:** [MASVS-CODE: Code Quality](https://mas.owasp.org/MASVS/10-MASVS-CODE)\n\nOverview\n--------\n\nAndroid applications can take advantage of native code written in languages like\nC and C++ for specific functionalities. However, when an application utilizes\nthe Java Native Interface (JNI) to interact with this native code, it\npotentially exposes itself to vulnerabilities like buffer overflows and other\nissues that may be present in the native code implementation.\n\nImpact\n------\n\nDespite very positive impacts such as performance optimization and obfuscation,\nutilizing native code in Android applications can have negative security\nimpacts. Native code languages like C/C++ lack the memory safety features of\nJava/Kotlin, making them susceptible to vulnerabilities like buffer overflows,\nuse-after-free errors, and other memory corruption issues -- leading to crashes\nor arbitrary code execution. Additionally, if a vulnerability exists in the\nnative code component, it can potentially compromise the entire application,\neven if the rest is written securely in Java.\n\nMitigations\n-----------\n\n### Development and coding guidance\n\n- **Secure Coding Guidelines**: For C/C++ projects, adhere to established secure coding standards (e.g., CERT, OWASP) to mitigate vulnerabilities like buffer overflows, integer overflows, and format string attacks. Prioritize libraries like Abseil known for quality and security. Whenever possible, consider adopting memory-safe languages like Rust, which offer performance comparable to C/C++.\n- **Input Validation**: Rigorously validate all input data received from external sources, including user input, network data, and files, to prevent injection attacks and other vulnerabilities.\n\n### Harden the compilation options\n\nNative libraries utilizing the ELF format can be hardened against a range of\nvulnerabilities by activating protective mechanisms like stack protection\n(Canary), relocation read-only (RELRO), data execution prevention (NX), and\nposition-independent executables (PIE). Conveniently, the Android NDK\ncompilation options already enable all these protections by default.\n\nTo verify the implementation of these security mechanisms within a binary, you\ncan employ tools like `hardening-check` or `pwntools`. \n\n### Bash\n\n $ pwn checksec --file path/to/libnativecode.so\n Arch: aarch64-64-little\n RELRO: Full RELRO\n Stack: Canary found\n NX: NX enabled\n PIE: PIE enabled\n\n### Verify third-party libraries are not vulnerable\n\nWhen choosing third-party libraries, prioritize using those with a solid\nreputation in the development community. Resources like the [Google Play SDK\nIndex](https://play.google.com/sdks) can help you identify well-regarded and trustworthy libraries. Ensure\nyou keep the libraries updated to the latest versions and proactively search for\nany known vulnerabilities related to them using resources like the databases\nfrom [Exploit-DB](https://www.exploit-db.com/). A web search using keywords like\n`[library_name] vulnerability` or `[library_name] CVE` can reveal critical\nsecurity information.\n\nResources\n---------\n\n- [CWE-111: Direct Use of Unsafe JNI](https://cwe.mitre.org/data/definitions/111.html)\n- [Exploit database](https://www.exploit-db.com/)\n- [Check binaries for security hardening features](https://www.systutorials.com/docs/linux/man/1-hardening-check/)\n- [Check binary security settings with pwntools](https://docs.pwntools.com/en/stable/commandline.html#pwn-checksec)\n- [Linux binary security hardening](https://medium.com/@n80fr1n60/linux-binary-security-hardening-1434e89a2525)\n- [Hardening ELF binaries using Relocation Read-Only (RELRO)](https://www.redhat.com/fr/blog/hardening-elf-binaries-using-relocation-read-only-relro)\n- [OWASP binary protection mechanisms](https://mas.owasp.org/MASTG/Android/0x05i-Testing-Code-Quality-and-Build-Settings/#binary-protection-mechanisms)\n- [SEI CERT Coding Standards](https://wiki.sei.cmu.edu/confluence/display/seccode/SEI+CERT+Coding+Standards)\n- [OWASP Developer Guide](https://owasp.org/www-project-developer-guide/release/)\n- [Google Play SDK Index](https://play.google.com/sdks)\n- [Android NDK](/ndk)\n- [Android Rust introduction](https://source.android.com/docs/setup/build/rust/building-rust-modules/overview)\n- [Abseil (C++ Common Libraries)](https://github.com/abseil/abseil-cpp)\n- [PIE is enforced by the linker](https://cs.android.com/android/platform/superproject/main/+/main:bionic/linker/linker_main.cpp;l=425?q=linker_main&ss=android%2Fplatform%2Fsuperproject%2Fmain)"]]