네이티브 코드 사용
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
OWASP 카테고리: MASVS-CODE: 코드 품질
개요
Android 애플리케이션은 특정 기능을 위해 C 및 C++와 같은 언어로 작성된 네이티브 코드를 활용할 수 있습니다. 그러나 애플리케이션이 Java Native Interface (JNI)를 사용하여 이 네이티브 코드와 상호작용할 때는 버퍼 오버플로 및 네이티브 코드 구현에 있을 수 있는 기타 문제와 같은 취약점에 노출될 수 있습니다.
영향
성능 최적화 및 난독화와 같은 매우 긍정적인 영향에도 불구하고 Android 애플리케이션에서 네이티브 코드를 활용하면 보안에 부정적인 영향을 미칠 수 있습니다. C/C++와 같은 네이티브 코드 언어에는 Java/Kotlin의 메모리 안전 기능이 없으므로 버퍼 오버플로, use-after-free 오류, 기타 메모리 손상 문제와 같은 취약점에 취약하여 비정상 종료 또는 임의 코드 실행이 발생할 수 있습니다. 또한 네이티브 코드 구성요소에 취약성이 있는 경우 나머지 부분이 Java로 안전하게 작성되어 있더라도 전체 애플리케이션이 손상될 수 있습니다.
완화 조치
개발 및 코딩 가이드
- 안전한 코딩 가이드라인: C/C++ 프로젝트의 경우 기존의 안전한 코딩 표준 (예: CERT, OWASP)를 사용하여 버퍼 오버플로, 정수 오버플로, 형식 문자열 공격과 같은 취약점을 완화합니다. 품질과 보안으로 유명한 Abseil과 같은 라이브러리를 우선적으로 사용합니다. 가능한 경우 C/C++와 비슷한 성능을 제공하는 Rust와 같은 메모리 안전 언어를 채택하는 것이 좋습니다.
- 입력 검증: 사용자 입력, 네트워크 데이터, 파일을 비롯하여 외부 소스에서 수신된 모든 입력 데이터를 엄격하게 검증하여 삽입 공격 및 기타 취약점을 방지합니다.
컴파일 옵션 강화
ELF 형식을 사용하는 네이티브 라이브러리는 스택 보호(캐나리아), 재배치 읽기 전용 (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
와 같은 키워드를 사용하여 웹을 검색하면 중요한 보안 정보가 유출될 수 있습니다.
리소스
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-26(UTC)
[[["이해하기 쉬움","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(UTC)"],[],[],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)"]]