ipa包完整性验证

这个是一个比较快速简单的实现方式,原理大概是通过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


推荐阅读更多精彩内容