這個是一個比較快速簡單的實現方式,原理大概是通過python腳本計算出需要檢查文件的hash值,寫入一個本地文件中。同樣在oc代碼中讀取需要檢查的文件,用同樣的方式計算出hash值,對比本地文件的hash值與計算的是否一致,如果一致則說明沒有被修改,否則就是被修改了可以上報或者退出程序。
readme
### checkipa.py
#### 用于安全審核檢查ipa的完整性,防止越獄手機動態修改plist或者其他文件
使用說明:
1.cd到workspace.app文件夾
2.執行命令 $ python checkipa.py
3.會自動生成appinfo.json 文件,里面為需要檢查的文件名和md5
4.appinfo.json 作為資源文件到工程中,或者直接在.app文件中加上此文件后打包
****
已知問題:不能知道二進制文件的md5值打包后因為簽名會改變,只能判斷資源文件
方案:如果需要判斷二進制文件的值可以通過server下發的方式,server獲取到ipa文件之后運行checkipa.py腳本,將生成的json作為網絡請求返回給客戶端,客戶端通過服務端返回的hash值,再計算出對應的hash值,再對比。
checkipa.py說明
需要添加檢查的腳本直接修改py即可
#需要檢查的文件名-目前只支持.app目錄下的文件,在數組中放入需要檢查的文件名即可
checklist = ['Info.plist','embedded.mobileprovision']
#md5規則自己定義 修改腳本和oc中對應的規則一致即可
md5 = (文件修改時間+文件md5)的字符串md5值
以下為appinfo.json 示例
{"Info.plist": "C61813D910C9A419758E53C33636D2A7", "embedded.mobileprovision": "239A9565E650216E2AEFCC4E29E376E0"}
checkipa.py
# coding: utf-8
# checkipa.py
import os
import shutil
import sys
import os.path
import time
import json
import hashlib
def file_exist(path):
if not os.path.isfile(path):
return False
if not os.access(path, os.R_OK):
return False
return True
def checkFileExist(checklist):
file_dir = os.getcwd()
print('currentPath:' + file_dir)
for checkFile in checklist:
allPath = file_dir + '/' + checkFile
print(allPath)
fileExist = file_exist(allPath)
if not fileExist:
print('文件不存在' + allPath)
return False
return True
def getStrMD5(string):
stringEncode = string.encode('utf8')
md5hash = hashlib.md5(stringEncode)
md5 = md5hash.hexdigest()
return str(md5).upper()
def getFileMD5(checkFilePath):
f = open(checkFilePath,'rb')
md5obj = hashlib.md5()
md5obj.update(f.read())
hash = md5obj.hexdigest()
f.close()
return str(hash).upper()
def getFileDic(checkFilePath):
fileJsonDic = {}
fileJsonDic['filePath'] = checkFilePath
fileCreatTime = os.path.getctime(checkFilePath)
fileJsonDic['fileCreateTime'] = fileCreatTime
fileModifyTime = int(os.path.getmtime(checkFilePath))
fileJsonDic['fileModifyTime'] = fileModifyTime
fileJsonDic['fileMd5'] = getFileMD5(checkFilePath)
fileEncap = str(fileModifyTime) + getFileMD5(checkFilePath)
fileJsonDic['fileEncap'] = fileEncap
fileJsonDic['fileEncapMd5'] = getStrMD5(fileEncap)
return fileJsonDic
def writeAppParams(checklist):
file_dir = os.getcwd()
#輸出所有需要的參數,用于調試
json_dir = file_dir + '/' + "app.json"
with open(json_dir, 'w') as f:
jsonDic = {}
for checkFileName in checklist:
checkFilePath = file_dir + '/' + checkFileName
checkFileDic = getFileDic(checkFilePath)
jsonDic[checkFileName] = checkFileDic
jsonStr = json.dumps(jsonDic)
f.write(jsonStr)
#生成檢查文件
check_json_dir = file_dir + '/' + "appinfo.json"
with open(check_json_dir, 'w') as f:
check_jsonDic = {}
for checkFileName in checklist:
checkFilePath = file_dir + '/' + checkFileName
checkFileDic = getFileDic(checkFilePath)
jsonDic[checkFileName] = checkFileDic['fileEncapMd5']
jsonStr = json.dumps(jsonDic)
f.write(jsonStr)
#刪除調試文件
os.remove(json_dir)
if __name__ == '__main__':
#需要檢查的文件
checklist = ['Info.plist','embedded.mobileprovision']
#1.判斷文件是否都存在
exist = checkFileExist(checklist)
if not exist:
print('檢查文件缺少,可能被移除')
sys.exit(-1)
print('繼續檢查')
#2.生成一個json記錄文件的creatTime和md5
writeAppParams(checklist)
print('檢查結束')
OC方法
.h
/**
檢查ipa文件是否被修改
*/
+ (void)checkIpaFile
.m
#import "CheckIPA.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCrypto.h>
#define FileHashDefaultChunkSizeForReadingData 1024*8
@implementation CheckIPA
/**
檢查ipa文件是否被修改
*/
+ (void)checkIpaFile{
NSString *checkFilePath = [[NSBundle mainBundle] pathForResource:@"appinfo.json" ofType:@""];
if (!(checkFilePath && checkFilePath.length > 0)) {
exit(0);
}
NSDictionary * dic;
if ([[NSFileManager defaultManager] fileExistsAtPath:checkFilePath]) {
NSString *checkFile = [NSString stringWithContentsOfFile:checkFilePath encoding:NSASCIIStringEncoding error:nil];
dic = [self getDicWithJsonString:checkFile];
}
// checklist--需要檢查的文件列表,需要與python腳本中的一致
// NSArray * arr = @[@"info.plist",@"embedded.mobileprovision"];
NSArray * arr = @[@"Info.plist"];
//讀取檢查文件中的md5值
for (NSString * fileName in arr) {
BOOL isMod = [self checkSameMD5:fileName dic:dic];
if (!isMod) {
exit(0);
}
}
}
+ (BOOL)checkSameMD5:(NSString*)fileName dic:(NSDictionary*)dic{
NSString * encapMd5 = dic[fileName];
if ([self stringIsNil:encapMd5]) {
return NO;
}
//讀取本地文件真實的md5
NSString *checkPath = [[NSBundle mainBundle] pathForResource:fileName ofType:@""];
if ([[NSFileManager defaultManager] fileExistsAtPath:checkPath]) {
NSString * md5 = [self getFileMD5WithPath:checkPath];
md5 = [md5 uppercaseString];
NSString * modTime = [self getFileModifyTime:checkPath];
if (![self stringIsNil:md5] && ![self stringIsNil:modTime]) {
NSString * encapStr = [NSString stringWithFormat:@"%@%@",modTime,md5];
NSString * encapStrMd5 = [[self stringToMD5:encapStr] uppercaseString];
NSLog(@"encapMd5,%@\n encapStrMd5:%@",encapMd5,encapStrMd5);
if ([encapStrMd5 isEqualToString:encapMd5]) {
return YES;
}
}
}
return NO;
}
+ (NSString *)getFileModifyTime:(NSString*)path{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:&error];
if (fileAttributes != nil) {
NSDate *fileModDate = [fileAttributes objectForKey:NSFileModificationDate];
if (fileModDate) {
NSLog(@"Modification date: %@\n", fileModDate);
NSString *timestamp = [NSString stringWithFormat:@"%.f", [fileModDate timeIntervalSince1970]];
return timestamp;
}
NSDate *fileCreateDate = [fileAttributes objectForKey:NSFileCreationDate];
if (fileCreateDate) {
NSLog(@"create date:%@\n", fileModDate);
}
NSNumber *fileSize = [fileAttributes objectForKey:NSFileSize];
if (fileSize) {
NSLog(@"File size: %qi\n", [fileSize unsignedLongLongValue]);
}
NSString *fileOwner = [fileAttributes objectForKey:NSFileOwnerAccountName];
if (fileOwner) {
NSLog(@"Owner: %@\n", fileOwner);
}
}
else {
NSLog(@"Path (%@) is invalid.", path);
return nil;
}
return nil;
}
+ (NSDictionary *)getDicWithJsonString:(NSString*)string{
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
if (!data) {
return nil;
}
NSError *error;
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if (jsonDic == nil || error != nil) {
NSLog(@"getArrWithJsonString fail:%@", error);
return nil;
}
return jsonDic;
}
+ (BOOL)stringIsNil:(NSString *)string {
if (string == nil || string == NULL || [string isKindOfClass:[NSNull class]] || [string isEqualToString:@""]) {
return YES;
}
return NO;
}
/**
獲取文件的MD5值
@param path 源文件路徑
@return MD5值字符串
*/
+ (NSString*)getFileMD5WithPath:(NSString*)path {
return (__bridge_transfer NSString *)FileMD5HashCreateWithPath((__bridge CFStringRef)path, FileHashDefaultChunkSizeForReadingData);
}
/**
獲取文件的MD5值,來源:http://www.cnblogs.com/visen-0/p/3160907.html
@Caller self
@param filePath 源文件路徑
@param chunkSizeForReadingData
@return MD5值字符串
*/
CFStringRef FileMD5HashCreateWithPath(CFStringRef filePath,size_t chunkSizeForReadingData) {
CFStringRef result = NULL;
CFReadStreamRef readStream = NULL;
CFURLRef fileURL =
CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
(CFStringRef)filePath,
kCFURLPOSIXPathStyle,
(Boolean)false);
if (!fileURL) goto done;
readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault,
(CFURLRef)fileURL);
if (!readStream) goto done;
bool didSucceed = (bool)CFReadStreamOpen(readStream);
if (!didSucceed) goto done;
CC_MD5_CTX hashObject;
CC_MD5_Init(&hashObject);
if (!chunkSizeForReadingData) {
chunkSizeForReadingData = FileHashDefaultChunkSizeForReadingData;
}
bool hasMoreData = true;
while (hasMoreData) {
uint8_t buffer[chunkSizeForReadingData];
CFIndex readBytesCount = CFReadStreamRead(readStream,(UInt8 *)buffer,(CFIndex)sizeof(buffer));
if (readBytesCount == -1) break;
if (readBytesCount == 0) {
hasMoreData = false;
continue;
}
CC_MD5_Update(&hashObject,(const void *)buffer,(CC_LONG)readBytesCount);
}
didSucceed = !hasMoreData;
unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5_Final(digest, &hashObject);
if (!didSucceed) goto done;
char hash[2 *sizeof(digest) + 1];
for (size_t i = 0; i < sizeof(digest); ++i) {
snprintf(hash + (2 *i), 3, "%02x", (int)(digest[i]));
}
result = CFStringCreateWithCString(kCFAllocatorDefault,(const char *)hash,kCFStringEncodingUTF8);
done:
if (readStream) {
CFReadStreamClose(readStream);
CFRelease(readStream);
}
if (fileURL) {
CFRelease(fileURL);
}
return result;
}
/**
字符串轉md5字符串
@param string 原始字符串
@return md5后的字符串
*/
+ (NSString *)stringToMD5:(NSString *)string
{
const char *cStr = [string UTF8String];
unsigned char digest[16];
CC_MD5( cStr, (CC_LONG)[string length], digest ); // This is the md5 call
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[output appendFormat:@"%02x", digest[i]];
}
return output;
}
@end