보안 배포 기준과 APK 검사 도구 추가
검토한 권한과 외부 공개 구성요소를 목록으로 관리한다. 배포 APK의 실제 서명과 인증서 및 해시와 크기 및 버전과 설치 번호를 대조하고 디버깅과 평문 통신 및 예상하지 않은 실행 파일을 검사한다. 기술 검사와 악성 코드 판정 및 배포 승인은 구분한다. 보안 업체에 탐지 근거를 확인하고 미해결 탐지가 있으면 새 APK 공개 배포를 보류하는 기준을 추가했다. 기존 인증서와 사용자 동의 기반 자체 업데이트를 유지한다. 탐지를 피하려는 패키지명·서명·코드 변형은 하지 않는다. README의 다운로드 링크는 최신 글이 고정되는 게시판으로 맞췄다. 기술 검사 단위 7개 통과. 실제 0.14.1 APK의 서명과 선언 및 배포 정보 일치를 확인했다. 잘못된 인증서 기준과 다른 파일 크기로 실행할 때 오류로 중단되는 것을 확인했다. 이 검사는 백신의 탐지 해제를 증명하지 않는다. 카스퍼스키의 구체적인 탐지 근거는 아직 확인하지 못했다. 앱 APK와 버전 및 운영 서비스와 회원 DB는 변경하지 않는다. 소스와 문서 변경만 반영한다. 기존 원문은 이전 Git 커밋과 로컬 work/security-policy-before에 보관했다. 기존 0.14.1 APK와 ZIP은 교체하지 않고 추가 문서와 도구를 포함한 소스 묶음을 별도로 남긴다.
This commit is contained in:
1 parent
8f566f5971
commit
839f1c386a
8 files changed
+428
-39
No files matched your search
@@ -0,0 +1,111 @@
|
||||
"""배포할 APK 자체의 권한과 공개 구성요소 및 서명과 버전 안내를 대조한다.
|
||||
|
||||
이 도구는 파일을 외부로 전송하지 않는다. 기술 검사 통과는 백신 판정이나
|
||||
배포 승인이 아니며 외부 탐지 검토는 보안 배포 기준에 따라 따로 확인한다.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
import zipfile
|
||||
|
||||
ANDROID = '{http://schemas.android.com/apk/res/android}'
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def inspect_manifest(xml, policy, release):
|
||||
root = ET.fromstring(xml)
|
||||
require(root.get('package') == policy['package'], '앱 식별자가 다릅니다.')
|
||||
require(root.get(ANDROID+'versionName') == release['appVersion'], '앱 버전이 배포 안내와 다릅니다.')
|
||||
require(root.get(ANDROID+'versionCode') == str(release['appVersionCode']), '설치 번호가 다릅니다.')
|
||||
sdk = root.find('uses-sdk')
|
||||
require(sdk is not None and int(sdk.get(ANDROID+'targetSdkVersion', '0')) >= policy['minimumTargetSdk'], '대상 Android 버전을 확인하세요.')
|
||||
# SDK 조건이 붙은 권한도 합쳐 검사한다. 새 권한을 다른 태그에 넣어 검사를 빠져나가지 못하게 한다.
|
||||
permissions = {node.get(ANDROID+'name', '') for node in root if node.tag.startswith('uses-permission')}
|
||||
unexpected = permissions - set(policy['permissions'])
|
||||
require(not unexpected, '검토되지 않은 권한: '+', '.join(sorted(unexpected)))
|
||||
app = root.find('application')
|
||||
require(app is not None, '앱 선언이 없습니다.')
|
||||
require(app.get(ANDROID+'debuggable', 'false') == 'false', '디버깅이 켜져 있습니다.')
|
||||
require(app.get(ANDROID+'testOnly', 'false') == 'false', '검사용 APK입니다.')
|
||||
require(app.get(ANDROID+'usesCleartextTraffic') == 'false', '평문 통신 차단 선언을 확인하세요.')
|
||||
require(app.get(ANDROID+'networkSecurityConfig') is None, '별도 네트워크 보안 설정은 수동 검토가 필요합니다.')
|
||||
exported = []
|
||||
for node in app:
|
||||
if node.tag not in {'activity', 'activity-alias', 'service', 'receiver', 'provider'}:
|
||||
continue
|
||||
name = node.get(ANDROID+'name', '')
|
||||
name = policy['package']+name if name.startswith('.') else name
|
||||
if '.' not in name:
|
||||
name = policy['package']+'.'+name
|
||||
# 선언 누락 시 Android 버전별 기본값이 달라질 수 있어 보수적으로 외부 공개로 취급한다.
|
||||
if node.get(ANDROID+'exported') == 'false':
|
||||
continue
|
||||
expected = policy['exportedComponents'].get(name)
|
||||
require(expected is not None, '공개 범위를 검토하지 않은 구성요소: '+name)
|
||||
require(node.tag == expected['tag'] and node.get(ANDROID+'permission', '') == expected['permission'], '공개 구성요소의 보호 권한이 다릅니다: '+name)
|
||||
exported.append(name)
|
||||
return {'permissions': sorted(permissions), 'exportedComponents': sorted(exported)}
|
||||
|
||||
|
||||
def run(command):
|
||||
# 셸을 거치지 않는다. 경로의 공백이나 특수문자를 명령으로 해석하지 않으며 비밀 서명 키도 읽지 않는다.
|
||||
result = subprocess.run([str(x) for x in command], capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=90)
|
||||
require(result.returncode == 0, 'SDK 검사 명령 실패: '+result.stderr.strip()[:600])
|
||||
return result.stdout
|
||||
|
||||
|
||||
def audit(apk, sdk, java, build_tools, command_tools, release, policy):
|
||||
digest = hashlib.sha256(apk.read_bytes()).hexdigest()
|
||||
require(digest == release['apkSha256'] and apk.stat().st_size == release['apkBytes'], 'APK 해시 또는 크기가 배포 안내와 다릅니다.')
|
||||
tools = sdk/'build-tools'/build_tools
|
||||
cli = sdk/'cmdline-tools'/command_tools
|
||||
signature = run([java, '-jar', tools/'lib/apksigner.jar', 'verify', '--print-certs', apk])
|
||||
certificates = re.findall(r'^Signer #\d+ certificate SHA-256 digest: ([0-9a-fA-F]{64})$', signature, re.M)
|
||||
require([x.lower() for x in certificates] == [policy['signerSha256']], '기존 배포의 서명 인증서와 다릅니다.')
|
||||
xml = run([java, '-Dcom.android.sdklib.toolsdir='+str(cli), '-classpath', cli/'lib/apkanalyzer-classpath.jar', 'com.android.tools.apk.analyzer.ApkAnalyzerCli', 'manifest', 'print', apk])
|
||||
report = inspect_manifest(xml, policy, release)
|
||||
with zipfile.ZipFile(apk) as archive:
|
||||
names = archive.namelist()
|
||||
require(len(names) == len(set(names)), 'APK에 중복 파일 경로가 있습니다.')
|
||||
# 현재 앱은 Kotlin과 Android 기본 기능만 사용한다. 실행 파일이나 네이티브 라이브러리가 추가되면 먼저 용도를 검토한다.
|
||||
unexpected = [name for name in names if name.lower().endswith(('.apk', '.jar', '.so', '.exe')) or (name.lower().endswith('.dex') and not re.fullmatch(r'classes(?:[2-9]|[1-9][0-9]+)?\.dex', name))]
|
||||
require(not unexpected, '추가 실행 파일 검토 필요: '+', '.join(unexpected))
|
||||
report.update({'package': policy['package'], 'version': release['appVersion'], 'sha256': digest, 'signerSha256': certificates[0].lower(), 'technicalChecks': 'passed', 'malwareVerdict': 'not_assessed', 'publicationApproval': 'not_assessed'})
|
||||
return report
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('apk', type=Path)
|
||||
parser.add_argument('--sdk', type=Path, required=True)
|
||||
parser.add_argument('--java', type=Path, required=True)
|
||||
parser.add_argument('--build-tools', default='36.0.0')
|
||||
parser.add_argument('--command-tools', default='latest')
|
||||
parser.add_argument('--release', type=Path, default=Path(__file__).resolve().parents[1]/'server/release.json')
|
||||
parser.add_argument('--policy', type=Path, default=Path(__file__).with_name('release_security_policy.json'))
|
||||
parser.add_argument('--output', type=Path)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
report = audit(args.apk.resolve(), args.sdk.resolve(), args.java.resolve(), args.build_tools, args.command_tools, json.loads(args.release.read_text(encoding='utf-8-sig')), json.loads(args.policy.read_text(encoding='utf-8-sig')))
|
||||
output = json.dumps(report, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
args.output.write_text(output+'\n', encoding='utf-8')
|
||||
print(output)
|
||||
print('기술 검사 통과. 외부 탐지 결과와 배포 승인 여부는 별도로 확인해야 합니다.')
|
||||
return 0
|
||||
except (ValueError, OSError, subprocess.TimeoutExpired, ET.ParseError, zipfile.BadZipFile) as error:
|
||||
print('배포 전 검사 실패: '+str(error), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user