示例#1
0
文件: validate.c 项目: 0neday/xpwn
static struct component_t *
parseManifest(Dictionary *manifest, int *plen)
{
	int i;
	struct component_t *array = NULL;
	int alen = 0, amax = 0;
	ArrayValue *buildIdentities = (ArrayValue *)getValueByKey(manifest, "BuildIdentities");
	if (!buildIdentities) {
		return NULL;
	}
	for (i = 0; i < buildIdentities->size; i++) {
		Dictionary *dict = (Dictionary *)buildIdentities->values[i];
		if (!dict) continue;
		dict = (Dictionary *)getValueByKey(dict, "Manifest");
		if (!dict) continue;
		for (dict = (Dictionary *)dict->values; dict; dict = (Dictionary*) dict->dValue.next) {
			DataValue *digest = (DataValue *)getValueByKey(dict, "Digest");
			Dictionary *info;
			StringValue *str;
			BoolValue *isfw;
			struct component_t *tmp;
			if (!digest) {
				continue;
			}
			if (alen >= amax) {
				amax = amax ? (amax * 2) : 1;
				tmp = realloc(array, amax * sizeof(struct component_t));
				if (!tmp) goto error;
				array = tmp;
			}
			tmp = array + alen++;
			tmp->key = dict->dValue.key;
			tmp->path = NULL;
			tmp->digest = digest;
			tmp->partial = (DataValue *)getValueByKey(dict, "PartialDigest");
			tmp->build = NULL;
			tmp->blob = NULL;
			tmp->required = FALSE;
			info = (Dictionary *)getValueByKey(dict, "Info");
			if (info) {
				str = (StringValue *)getValueByKey(info, "Path");
				if (str) {
					tmp->path = str->value;
				}
				isfw = (BoolValue *)getValueByKey(info, "IsFirmwarePayload");
				tmp->required = (isfw && isfw->value) || !strcmp(tmp->key, "KernelCache");
			}
			str = (StringValue *)getValueByKey(dict, "BuildString");
			if (str) {
				tmp->build = str->value;
			}
		}
	}
	*plen = alen;
	return array;
error:
	free(array);
	*plen = 0;
	return NULL;
}
示例#2
0
/****************************************************************************
 * 处理一个字符串,其中有多个形如"key:value\n"的行. 
 *      从__source中将key对应的value取出并存放在__value中
 * name parseValueByKey
 * input : __source
 *          __key
 * output: __value
 * return no
 * other: 
 ****************************************************************************/
int parseValueByKey(char *__source /** input **/, char* __key/** input **/, char* __value/** output **/)
{
    char* ptrSrc = NULL;
    char* ptrNext = NULL;
    char* ptrValue = NULL;

    if((__source== NULL) || (__key == NULL) || __value == NULL)
    {
        return 0;
    }

    *__value = '\0';
    ptrSrc = __source;
    ptrNext = __source;
    while(ptrNext != NULL/** 最后一行已经处理完成 **/)
    {
        ptrNext = strGetLine(ptrSrc);               /** 先找到并保存下一行的地址 **/
        ptrValue = getValueByKey(ptrSrc, __key);    /** 找到了行结束符 **/
        if(ptrValue == NULL)                        /** 找不到键,或有键无值 **/
        {
            //printf("[key:NoValue]-[%s-%s]\n", ptrKey, ptrSrc);
            //continue;
        }
        else
        {
            strcpy(__value, ptrValue);
            //printf("[key:value]-[%s-%s]\n", ptrKey, ptrValue);
        }
        ptrSrc = ptrNext;
        //printf("[%s-%d]ptrNext[%s]/ptrValue[%s]!\n", __FILE__, __LINE__, ptrNext,  ptrValue);
    }
    return  1;
}
示例#3
0
文件: pwnutil.c 项目: 0neday/xpwn
void fixupBootNeuterArgs(Volume* volume, char unlockBaseband, char selfDestruct, char use39, char use46) {
	const char bootNeuterPlist[] = "/System/Library/LaunchDaemons/com.devteam.bootneuter.auto.plist";
	AbstractFile* plistFile;
	char* plist;
	Dictionary* info;
	size_t bufferSize;
	ArrayValue* arguments;
	
	XLOG(0, "fixing up BootNeuter arguments...\n");
	
	plist = malloc(1);
	bufferSize = 0;
	plistFile = createAbstractFileFromMemoryFile((void**)&plist, &bufferSize);
	get_hfs(volume, bootNeuterPlist, plistFile);	
	plistFile->close(plistFile);
	info = createRoot(plist);
	free(plist);

	arguments = (ArrayValue*) getValueByKey(info, "ProgramArguments");
	addStringToArray(arguments, "-autoMode");
	addStringToArray(arguments, "YES");
	addStringToArray(arguments, "-RegisterForSystemEvents");
	addStringToArray(arguments, "YES");
	
	if(unlockBaseband) {
		addStringToArray(arguments, "-unlockBaseband");
		addStringToArray(arguments, "YES");
	}
	
	if(selfDestruct) {
		addStringToArray(arguments, "-selfDestruct");
		addStringToArray(arguments, "YES");
	}
	
	if(use39) {
		addStringToArray(arguments, "-bootLoader");
		addStringToArray(arguments, "3.9");
	} else if(use46) {
		addStringToArray(arguments, "-bootLoader");
		addStringToArray(arguments, "4.6");
	}
	
	plist = getXmlFromRoot(info);
	releaseDictionary(info);
	
	plistFile = createAbstractFileFromMemory((void**)&plist, sizeof(char) * strlen(plist));
	add_hfs(volume, plistFile, bootNeuterPlist);
	free(plist);
}
示例#4
0
文件: patch.c 项目: 0x76/opensn0w
Dictionary *get_key_dictionary_from_bundle(char *member)
{
	firmwarePatches = (Dictionary *) getValueByKey(info, "FirmwareKeys");
	patchDict = (Dictionary *) firmwarePatches->values;

	if (!strcasecmp(patchDict->dValue.key, member))
		return patchDict;

	while (patchDict != NULL) {
		if (!strcasecmp(patchDict->dValue.key, member))
			return patchDict;

		patchDict = (Dictionary *) patchDict->dValue.next;
	}

	return NULL;
}
示例#5
0
	T get(const string& key)
	{
		return boost::any_cast<const T&>(getValueByKey(key));
	}
示例#6
0
void find_apt(COMMAND cmd, ApartmentTable db) {
    /*
     * find_apt
     * Printing the apartments that matched the cmd->kwargs filter
     */

    // Pre sorting the array tto enable sorting view
    BOOL isAllocated = FALSE;
    ApartmentTable ptr = db;
    if (isKeyExists("s", cmd.kwargs)) {
        // ASC - low to high
        ptr = sortTable(db, FALSE);
        isAllocated = TRUE;
    } else if (isKeyExists("sr", cmd.kwargs)) {
        // DESC - high to low
        ptr = sortTable(db, TRUE);
        isAllocated = TRUE;
    }

    for (int i = 0; i < db.size; i++) {
        Apartment tmp = ptr.arr[i];
        time_t d1, d2;
        char *pt;
        // if apartment not match the filter, we continue to the next

        pt = getValueByKey("MaxPrice", cmd.kwargs);
        int price = (int) (pt ? atoi(pt) : NULL);
        if (price && tmp.price > price)
            continue;

        pt = getValueByKey("MinNumRooms", cmd.kwargs);
        int rooms = (int) (pt ? atoi(pt) : NULL);
        if (rooms && tmp.rooms < rooms)
            continue;

        pt = getValueByKey("MaxNumRooms", cmd.kwargs);
        rooms = (int) (pt ? atoi(pt) : NULL);
        if (rooms && tmp.rooms > rooms)
            continue;


        // return all apartments that was inserted @dayBack ago
        pt = getValueByKey("Enter", cmd.kwargs);
        int dayBack = (int) (pt ? atoi(pt) : NULL);
        if (dayBack > 0) {
            struct tm entryDate;
            int now = (int) time(NULL);
            now = now - (84600 * dayBack);

            entryDate.tm_hour = 23;
            entryDate.tm_min = 59;
            entryDate.tm_sec = 59;
            entryDate.tm_year = tmp.entry_year + 100;
            entryDate.tm_mon = tmp.entry_month - 1;
            entryDate.tm_mday = tmp.entry_day;

            d1 = mktime(&entryDate);
            if (now - d1  > 0)
                continue;
        }

        char* date = getValueByKey("Date", cmd.kwargs);
        if (date != NULL) {
            struct tm endDate;
            struct tm startDate;
            endDate.tm_hour = 23;
            endDate.tm_min = 59;
            endDate.tm_sec = 59;
            endDate.tm_year = atoi(substring(date, 5 , 4)) - 1900;
            endDate.tm_mon = atoi(substring(date, 3 , 2)) - 1;
            endDate.tm_mday = atoi(substring(date, 1 , 2));

            startDate.tm_hour = 23;
            startDate.tm_min = 59;
            startDate.tm_sec = 59;
            startDate.tm_year = tmp.entry_year + 100;
            startDate.tm_mon = tmp.entry_month - 1;
            startDate.tm_mday = tmp.entry_day;

            d1 = mktime(&endDate);
            d2 = mktime(&startDate);
            if (d2 - d1 > 0)
                continue;
        }

        printApartment(tmp);
    }

    if (isAllocated == TRUE) {
        // free the memory that allocated if the array is sorted
        //free(ptr.arr);
    }
}
示例#7
0
文件: main.c 项目: OPK/xpwn
int main(int argc, char* argv[]) {
    init_libxpwn();

    Dictionary* info;
    Dictionary* firmwarePatches;
    Dictionary* patchDict;
    ArrayValue* patchArray;

    void* buffer;

    StringValue* actionValue;
    StringValue* pathValue;

    StringValue* fileValue;

    StringValue* patchValue;
    char* patchPath;

    char* rootFSPathInIPSW;
    io_func* rootFS;
    Volume* rootVolume;
    size_t rootSize;
    size_t preferredRootSize = 0;
    size_t minimumRootSize = 0;

    char* ramdiskFSPathInIPSW;
    unsigned int ramdiskKey[16];
    unsigned int ramdiskIV[16];
    unsigned int* pRamdiskKey = NULL;
    unsigned int* pRamdiskIV = NULL;
    io_func* ramdiskFS;
    Volume* ramdiskVolume;

    char* updateRamdiskFSPathInIPSW = NULL;

    int i;

    OutputState* outputState;

    char* bundlePath;
    char* bundleRoot = "FirmwareBundles/";

    int mergePaths;
    char* outputIPSW;

    void* imageBuffer;
    size_t imageSize;

    AbstractFile* bootloader39 = NULL;
    AbstractFile* bootloader46 = NULL;
    AbstractFile* applelogo = NULL;
    AbstractFile* recoverymode = NULL;

    char noWipe = FALSE;

    char unlockBaseband = FALSE;
    char selfDestruct = FALSE;
    char use39 = FALSE;
    char use46 = FALSE;
    char doBootNeuter = FALSE;
    char updateBB = FALSE;
    char useMemory = FALSE;

    unsigned int key[16];
    unsigned int iv[16];

    unsigned int* pKey = NULL;
    unsigned int* pIV = NULL;

    if(argc < 3) {
        XLOG(0, "usage %s <input.ipsw> <target.ipsw> [-b <bootimage.png>] [-r <recoveryimage.png>] [-s <system partition size>] [-memory] [-bbupdate] [-nowipe] [-e \"<action to exclude>\"] [[-unlock] [-use39] [-use46] [-cleanup] -3 <bootloader 3.9 file> -4 <bootloader 4.6 file>] <package1.tar> <package2.tar>...\n", argv[0]);
        return 0;
    }

    outputIPSW = argv[2];

    int* toRemove = NULL;
    int numToRemove = 0;

    for(i = 3; i < argc; i++) {
        if(argv[i][0] != '-') {
            break;
        }

        if(strcmp(argv[i], "-memory") == 0) {
            useMemory = TRUE;
            continue;
        }

        if(strcmp(argv[i], "-s") == 0) {
            int size;
            sscanf(argv[i + 1], "%d", &size);
            preferredRootSize = size;
            i++;
            continue;
        }

        if(strcmp(argv[i], "-nowipe") == 0) {
            noWipe = TRUE;
            continue;
        }

        if(strcmp(argv[i], "-bbupdate") == 0) {
            updateBB = TRUE;
            continue;
        }

        if(strcmp(argv[i], "-e") == 0) {
            numToRemove++;
            toRemove = realloc(toRemove, numToRemove * sizeof(int));
            toRemove[numToRemove - 1] = i + 1;
            i++;
            continue;
        }

        if(strcmp(argv[i], "-unlock") == 0) {
            unlockBaseband = TRUE;
            continue;
        }

        if(strcmp(argv[i], "-cleanup") == 0) {
            selfDestruct = TRUE;
            continue;
        }

        if(strcmp(argv[i], "-use39") == 0) {
            if(use46) {
                XLOG(0, "error: select only one of -use39 and -use46\n");
                exit(1);
            }
            use39 = TRUE;
            continue;
        }

        if(strcmp(argv[i], "-use46") == 0) {
            if(use39) {
                XLOG(0, "error: select only one of -use39 and -use46\n");
                exit(1);
            }
            use46 = TRUE;
            continue;
        }

        if(strcmp(argv[i], "-b") == 0) {
            applelogo = createAbstractFileFromFile(fopen(argv[i + 1], "rb"));
            if(!applelogo) {
                XLOG(0, "cannot open %s\n", argv[i + 1]);
                exit(1);
            }
            i++;
            continue;
        }

        if(strcmp(argv[i], "-r") == 0) {
            recoverymode = createAbstractFileFromFile(fopen(argv[i + 1], "rb"));
            if(!recoverymode) {
                XLOG(0, "cannot open %s\n", argv[i + 1]);
                exit(1);
            }
            i++;
            continue;
        }

        if(strcmp(argv[i], "-3") == 0) {
            bootloader39 = createAbstractFileFromFile(fopen(argv[i + 1], "rb"));
            if(!bootloader39) {
                XLOG(0, "cannot open %s\n", argv[i + 1]);
                exit(1);
            }
            i++;
            continue;
        }

        if(strcmp(argv[i], "-4") == 0) {
            bootloader46 = createAbstractFileFromFile(fopen(argv[i + 1], "rb"));
            if(!bootloader46) {
                XLOG(0, "cannot open %s\n", argv[i + 1]);
                exit(1);
            }
            i++;
            continue;
        }
    }

    mergePaths = i;

    if(use39 || use46 || unlockBaseband || selfDestruct || bootloader39 || bootloader46) {
        if(!(bootloader39) || !(bootloader46)) {
            XLOG(0, "error: you must specify both bootloader files.\n");
            exit(1);
        } else {
            doBootNeuter = TRUE;
        }
    }

    info = parseIPSW2(argv[1], bundleRoot, &bundlePath, &outputState, useMemory);
    if(info == NULL) {
        XLOG(0, "error: Could not load IPSW\n");
        exit(1);
    }

    firmwarePatches = (Dictionary*)getValueByKey(info, "FilesystemPatches");

    int j;
    for(j = 0; j < numToRemove; j++) {
        removeKey(firmwarePatches, argv[toRemove[j]]);
    }
    free(toRemove);

    firmwarePatches = (Dictionary*)getValueByKey(info, "FirmwarePatches");
    patchDict = (Dictionary*) firmwarePatches->values;
    while(patchDict != NULL) {
        fileValue = (StringValue*) getValueByKey(patchDict, "File");

        StringValue* keyValue = (StringValue*) getValueByKey(patchDict, "Key");
        StringValue* ivValue = (StringValue*) getValueByKey(patchDict, "IV");
        pKey = NULL;
        pIV = NULL;

        if(keyValue) {
            sscanf(keyValue->value, "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
                   &key[0], &key[1], &key[2], &key[3], &key[4], &key[5], &key[6], &key[7], &key[8],
                   &key[9], &key[10], &key[11], &key[12], &key[13], &key[14], &key[15]);

            pKey = key;
        }

        if(ivValue) {
            sscanf(ivValue->value, "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
                   &iv[0], &iv[1], &iv[2], &iv[3], &iv[4], &iv[5], &iv[6], &iv[7], &iv[8],
                   &iv[9], &iv[10], &iv[11], &iv[12], &iv[13], &iv[14], &iv[15]);
            pIV = iv;
        }

        if(strcmp(patchDict->dValue.key, "Restore Ramdisk") == 0) {
            ramdiskFSPathInIPSW = fileValue->value;
            if(pKey) {
                memcpy(ramdiskKey, key, sizeof(key));
                memcpy(ramdiskIV, iv, sizeof(iv));
                pRamdiskKey = ramdiskKey;
                pRamdiskIV = ramdiskIV;
            } else {
                pRamdiskKey = NULL;
                pRamdiskIV = NULL;
            }
        }

        if(strcmp(patchDict->dValue.key, "Update Ramdisk") == 0) {
            updateRamdiskFSPathInIPSW = fileValue->value;
        }

        patchValue = (StringValue*) getValueByKey(patchDict, "Patch2");
        if(patchValue) {
            if(noWipe) {
                XLOG(0, "%s: ", patchDict->dValue.key);
                fflush(stdout);
                doPatch(patchValue, fileValue, bundlePath, &outputState, pKey, pIV, useMemory);
                patchDict = (Dictionary*) patchDict->dValue.next;
                continue; /* skip over the normal Patch */
            }
        }

        patchValue = (StringValue*) getValueByKey(patchDict, "Patch");
        if(patchValue) {
            XLOG(0, "%s: ", patchDict->dValue.key);
            fflush(stdout);
            doPatch(patchValue, fileValue, bundlePath, &outputState, pKey, pIV, useMemory);
        }

        if(strcmp(patchDict->dValue.key, "AppleLogo") == 0 && applelogo) {
            XLOG(0, "replacing %s\n", fileValue->value);
            fflush(stdout);
            ASSERT((imageBuffer = replaceBootImage(getFileFromOutputState(&outputState, fileValue->value), pKey, pIV, applelogo, &imageSize)) != NULL, "failed to use new image");
            addToOutput(&outputState, fileValue->value, imageBuffer, imageSize);
        }

        if(strcmp(patchDict->dValue.key, "RecoveryMode") == 0 && recoverymode) {
            XLOG(0, "replacing %s\n", fileValue->value);
            fflush(stdout);
            ASSERT((imageBuffer = replaceBootImage(getFileFromOutputState(&outputState, fileValue->value), pKey, pIV, recoverymode, &imageSize)) != NULL, "failed to use new image");
            addToOutput(&outputState, fileValue->value, imageBuffer, imageSize);
        }

        patchDict = (Dictionary*) patchDict->dValue.next;
    }

    fileValue = (StringValue*) getValueByKey(info, "RootFilesystem");
    rootFSPathInIPSW = fileValue->value;

    size_t defaultRootSize = ((IntegerValue*) getValueByKey(info, "RootFilesystemSize"))->value;
    minimumRootSize = defaultRootSize * 1000 * 1000;
    minimumRootSize -= minimumRootSize % 512;

    if(preferredRootSize == 0) {
        preferredRootSize = defaultRootSize;
    }

    rootSize =  preferredRootSize * 1000 * 1000;
    rootSize -= rootSize % 512;

    if(useMemory) {
        buffer = malloc(rootSize);
    } else {
        buffer = NULL;
    }

    if(buffer == NULL) {
        XLOG(2, "using filesystem backed temporary storage\n");
    }

    extractDmg(
        createAbstractFileFromFileVault(getFileFromOutputState(&outputState, rootFSPathInIPSW), ((StringValue*)getValueByKey(info, "RootFilesystemKey"))->value),
        openRoot((void**)&buffer, &rootSize), -1);


    rootFS = IOFuncFromAbstractFile(openRoot((void**)&buffer, &rootSize));
    rootVolume = openVolume(rootFS);
    XLOG(0, "Growing root to minimum: %ld\n", (long) defaultRootSize);
    fflush(stdout);
    grow_hfs(rootVolume, minimumRootSize);
    if(rootSize > minimumRootSize) {
        XLOG(0, "Growing root: %ld\n", (long) preferredRootSize);
        fflush(stdout);
        grow_hfs(rootVolume, rootSize);
    }

    firmwarePatches = (Dictionary*)getValueByKey(info, "FilesystemPatches");
    patchArray = (ArrayValue*) firmwarePatches->values;
    while(patchArray != NULL) {
        for(i = 0; i < patchArray->size; i++) {
            patchDict = (Dictionary*) patchArray->values[i];
            fileValue = (StringValue*) getValueByKey(patchDict, "File");

            actionValue = (StringValue*) getValueByKey(patchDict, "Action");
            if(strcmp(actionValue->value, "ReplaceKernel") == 0) {
                pathValue = (StringValue*) getValueByKey(patchDict, "Path");
                XLOG(0, "replacing kernel... %s -> %s\n", fileValue->value, pathValue->value);
                fflush(stdout);
                add_hfs(rootVolume, getFileFromOutputState(&outputState, fileValue->value), pathValue->value);
            }
            if(strcmp(actionValue->value, "Patch") == 0) {
                patchValue = (StringValue*) getValueByKey(patchDict, "Patch");
                patchPath = (char*) malloc(sizeof(char) * (strlen(bundlePath) + strlen(patchValue->value) + 2));
                strcpy(patchPath, bundlePath);
                strcat(patchPath, "/");
                strcat(patchPath, patchValue->value);

                XLOG(0, "patching %s (%s)... ", fileValue->value, patchPath);
                doPatchInPlace(rootVolume, fileValue->value, patchPath);
                free(patchPath);
            }
        }

        patchArray = (ArrayValue*) patchArray->dValue.next;
    }

    for(; mergePaths < argc; mergePaths++) {
        XLOG(0, "merging %s\n", argv[mergePaths]);
        AbstractFile* tarFile = createAbstractFileFromFile(fopen(argv[mergePaths], "rb"));
        if(tarFile == NULL) {
            XLOG(1, "cannot find %s, make sure your slashes are in the right direction\n", argv[mergePaths]);
            releaseOutput(&outputState);
            closeRoot(buffer);
            exit(0);
        }
        hfs_untar(rootVolume, tarFile);
        tarFile->close(tarFile);
    }

    if(pRamdiskKey) {
        ramdiskFS = IOFuncFromAbstractFile(openAbstractFile2(getFileFromOutputStateForOverwrite(&outputState, ramdiskFSPathInIPSW), pRamdiskKey, pRamdiskIV));
    } else {
        XLOG(0, "unencrypted ramdisk\n");
        ramdiskFS = IOFuncFromAbstractFile(openAbstractFile(getFileFromOutputStateForOverwrite(&outputState, ramdiskFSPathInIPSW)));
    }
    ramdiskVolume = openVolume(ramdiskFS);
    XLOG(0, "growing ramdisk: %d -> %d\n", ramdiskVolume->volumeHeader->totalBlocks * ramdiskVolume->volumeHeader->blockSize, (ramdiskVolume->volumeHeader->totalBlocks + 4) * ramdiskVolume->volumeHeader->blockSize);
    grow_hfs(ramdiskVolume, (ramdiskVolume->volumeHeader->totalBlocks + 4) * ramdiskVolume->volumeHeader->blockSize);

    if(doBootNeuter) {
        firmwarePatches = (Dictionary*)getValueByKey(info, "BasebandPatches");
        if(firmwarePatches != NULL) {
            patchDict = (Dictionary*) firmwarePatches->values;
            while(patchDict != NULL) {
                pathValue = (StringValue*) getValueByKey(patchDict, "Path");

                fileValue = (StringValue*) getValueByKey(patchDict, "File");
                if(fileValue) {
                    XLOG(0, "copying %s -> %s... ", fileValue->value, pathValue->value);
                    fflush(stdout);
                    if(copyAcrossVolumes(ramdiskVolume, rootVolume, fileValue->value, pathValue->value)) {
                        patchValue = (StringValue*) getValueByKey(patchDict, "Patch");
                        if(patchValue) {
                            patchPath = malloc(sizeof(char) * (strlen(bundlePath) + strlen(patchValue->value) + 2));
                            strcpy(patchPath, bundlePath);
                            strcat(patchPath, "/");
                            strcat(patchPath, patchValue->value);
                            XLOG(0, "patching %s (%s)... ", pathValue->value, patchPath);
                            fflush(stdout);
                            doPatchInPlace(rootVolume, pathValue->value, patchPath);
                            free(patchPath);
                        }
                    }
                }

                if(strcmp(patchDict->dValue.key, "Bootloader 3.9") == 0 && bootloader39 != NULL) {
                    add_hfs(rootVolume, bootloader39, pathValue->value);
                }

                if(strcmp(patchDict->dValue.key, "Bootloader 4.6") == 0 && bootloader46 != NULL) {
                    add_hfs(rootVolume, bootloader46, pathValue->value);
                }

                patchDict = (Dictionary*) patchDict->dValue.next;
            }
        }

        fixupBootNeuterArgs(rootVolume, unlockBaseband, selfDestruct, use39, use46);
    }

    createRestoreOptions(ramdiskVolume, preferredRootSize, updateBB);
    closeVolume(ramdiskVolume);
    CLOSE(ramdiskFS);

    if(updateRamdiskFSPathInIPSW)
        removeFileFromOutputState(&outputState, updateRamdiskFSPathInIPSW);

    closeVolume(rootVolume);
    CLOSE(rootFS);

    buildDmg(openRoot((void**)&buffer, &rootSize), getFileFromOutputStateForReplace(&outputState, rootFSPathInIPSW));

    closeRoot(buffer);

    writeOutput(&outputState, outputIPSW);

    releaseDictionary(info);

    free(bundlePath);

    return 0;
}
示例#8
0
文件: pwnutil.c 项目: 0neday/xpwn
int mergeIdentities(Dictionary* manifest, AbstractFile *idFile) {
	char *disk = NULL;
	Dictionary *dict;
	StringValue *path;
	StringValue *mainBuildVersion, *buildVersion;

	mainBuildVersion = (StringValue *)getValueByKey(manifest, "ProductBuildVersion");
	if (!mainBuildVersion) {
		return -1;
	}

	ArrayValue *buildIdentities = (ArrayValue *)getValueByKey(manifest, "BuildIdentities");
	if (buildIdentities && buildIdentities->size) {
		dict = (Dictionary *)buildIdentities->values[0];
		if (!dict) return -1;
		dict = (Dictionary *)getValueByKey(dict, "Manifest");
		if (!dict) return -1;
		dict = (Dictionary *)getValueByKey(dict, "RestoreRamDisk");
		if (!dict) return -1;
		dict = (Dictionary *)getValueByKey(dict, "Info");
		if (!dict) return -1;
		path = (StringValue *)getValueByKey(dict, "Path");
		if (!path) return -1;
		disk = strdup(path->value);
	}
	if (!disk) {
		return -1;
	}

	Dictionary* id = NULL;
	size_t fileLength = idFile->getLength(idFile);
	char *plist = malloc(fileLength);
	idFile->read(idFile, plist, fileLength);
	id = createRoot(plist);
	free(plist);

	buildVersion = (StringValue *)getValueByKey(manifest, "ProductBuildVersion");
	if (!buildVersion || strcmp(mainBuildVersion->value, buildVersion->value)) {
		return -1;
	}

	ArrayValue *newIdentities = (ArrayValue *)getValueByKey(id, "BuildIdentities");
	if (newIdentities && newIdentities->size) {
		dict = (Dictionary *)newIdentities->values[0];
		if (!dict) return -1;
		dict = (Dictionary *)getValueByKey(dict, "Manifest");
		if (!dict) return -1;
		dict = (Dictionary *)getValueByKey(dict, "RestoreRamDisk");
		if (!dict) return -1;
		dict = (Dictionary *)getValueByKey(dict, "Info");
		if (!dict) return -1;
		path = (StringValue *)getValueByKey(dict, "Path");
		if (!path) return -1;
		free(path->value);
		path->value = disk;
		prependToArray(buildIdentities, newIdentities->values[0]);
		unlinkValueFromDictionary(id, (DictValue *)newIdentities);
		releaseDictionary(id);
		releaseArrayEx(newIdentities, 0);
		return 0;
	}

	return -1;
}
示例#9
0
文件: pwnutil.c 项目: 0neday/xpwn
Dictionary* parseIPSW2(const char* inputIPSW, const char* bundleRoot, char** bundlePath, OutputState** state, int useMemory) {
	Dictionary* info;
	char* infoPath;

	AbstractFile* plistFile;
	char* plist;
	FILE* inputIPSWFile;

	SHA_CTX sha1_ctx;
	char* buffer;
	int read;
	unsigned char hash[20];

	DIR* dir;
	struct dirent* ent;
	StringValue* plistSHA1String;
	unsigned int plistHash[20];
	int i;

	*bundlePath = NULL;

	inputIPSWFile = fopen(inputIPSW, "rb");
	if(!inputIPSWFile) {
		return NULL;
	}

	XLOG(0, "Hashing IPSW...\n");

	buffer = malloc(BUFFERSIZE);
	SHA1_Init(&sha1_ctx);
	while(!feof(inputIPSWFile)) {
		read = fread(buffer, 1, BUFFERSIZE, inputIPSWFile);
		SHA1_Update(&sha1_ctx, buffer, read);
	}
	SHA1_Final(hash, &sha1_ctx);
	free(buffer);

	fclose(inputIPSWFile);

	XLOG(0, "Matching IPSW in %s... (%02x%02x%02x%02x...)\n", bundleRoot, (int) hash[0], (int) hash[1], (int) hash[2], (int) hash[3]);

	dir = opendir(bundleRoot);
	if(dir == NULL) {
		XLOG(1, "Bundles directory not found\n");
		return NULL;
	}

	while((ent = readdir(dir)) != NULL) {
		if(ent->d_name[0] == '.' && (ent->d_name[1] == '\0' || (ent->d_name[1] == '.' && ent->d_name[2] == '\0'))) {
			continue;
		}

		infoPath = (char*) malloc(sizeof(char) * (strlen(bundleRoot) + sizeof(PATH_SEPARATOR) + strlen(ent->d_name) + sizeof(PATH_SEPARATOR "Info.plist")));
		sprintf(infoPath, "%s" PATH_SEPARATOR "%s" PATH_SEPARATOR "Info.plist", bundleRoot, ent->d_name);
		XLOG(0, "checking: %s\n", infoPath);

		if((plistFile = createAbstractFileFromFile(fopen(infoPath, "rb"))) != NULL) {
			plist = (char*) malloc(plistFile->getLength(plistFile));
			plistFile->read(plistFile, plist, plistFile->getLength(plistFile));
			plistFile->close(plistFile);
			info = createRoot(plist);
			free(plist);

			plistSHA1String = (StringValue*)getValueByKey(info, "SHA1");
			if(plistSHA1String) {
				sscanf(plistSHA1String->value, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
					&plistHash[0], &plistHash[1], &plistHash[2], &plistHash[3], &plistHash[4],
					&plistHash[5], &plistHash[6], &plistHash[7], &plistHash[8], &plistHash[9],
					&plistHash[10], &plistHash[11], &plistHash[12], &plistHash[13], &plistHash[14],
					&plistHash[15], &plistHash[16], &plistHash[17], &plistHash[18], &plistHash[19]);

				for(i = 0; i < 20; i++) {
					if(plistHash[i] != hash[i]) {
						break;
					}
				}

				if(i == 20) {
					*bundlePath = (char*) malloc(sizeof(char) * (strlen(bundleRoot) + sizeof(PATH_SEPARATOR) + strlen(ent->d_name)));
					sprintf(*bundlePath, "%s" PATH_SEPARATOR "%s", bundleRoot, ent->d_name);

					free(infoPath);
					break;
				}
			}

			releaseDictionary(info);
		}

		free(infoPath);
	}

	closedir(dir);

	if(*bundlePath == NULL) {
		return NULL;
	}

	*state = loadZip2(inputIPSW, useMemory);

	return info;
}
示例#10
0
文件: validate.c 项目: 0neday/xpwn
int main(int argc, char* argv[]) {
	init_libxpwn(&argc, argv);

	OutputState *outputState;
	size_t fileLength;

	AbstractFile *signFile;
	Dictionary *signDict = NULL;
	DataValue *ticket;
	Dictionary *dict;

	AbstractFile *manifestFile;
	Dictionary* manifest;
	struct component_t *array;

	char *plist;
	int i, j, n;
	int rv, error = 0;

	X509 *x0, *y1, *y2;
	uint64_t savecid = 0;
	const unsigned char *p;

	int verbose = FALSE;
	int fromzip = FALSE;

	if (argc < 3) {
		XLOG(0, "usage %s file.shsh BuildManifest.plist [-v] [-z]\n", argv[0]);
		return 0;
	}

	for (i = 3; i < argc; i++) {
		if (!strcmp(argv[i], "-v")) {
			verbose = TRUE;
			continue;
		}

		if (!strcmp(argv[i], "-z")) {
			fromzip = TRUE;
			continue;
		}
	}

	// XXX handle gzip/bplist files
	signFile = createAbstractFileFromFile(fopen(argv[1], "rb"));
	if (!signFile) {
		XLOG(0, "FATAL: cannot open %s\n", argv[1]);
		exit(1);
	}

	fileLength = signFile->getLength(signFile);
	plist = malloc(fileLength);
	signFile->read(signFile, plist, fileLength);
	signFile->close(signFile);
	signDict = createRoot(plist);
	free(plist);

	if (!signDict) {
		XLOG(0, "FATAL: cannot parse %s\n", argv[1]);
		exit(1);
	}

	MaxLoadZipSize = 128 * 1024;
	if (fromzip) {
		outputState = loadZip2(argv[2], TRUE); // XXX ASSERT
		manifestFile = getFileFromOutputState(&outputState, "BuildManifest.plist");
	} else {
		outputState = NULL;
		manifestFile = createAbstractFileFromFile(fopen(argv[2], "rb"));
	}
	if (!manifestFile) {
		XLOG(0, "FATAL: cannot open %s\n", argv[2]);
		exit(1);
	}

	fileLength = manifestFile->getLength(manifestFile);
	plist = malloc(fileLength);
	manifestFile->read(manifestFile, plist, fileLength);
	manifestFile->close(manifestFile);
	manifest = createRoot(plist);
	free(plist);

	if (!manifest) {
		XLOG(0, "FATAL: cannot parse %s\n", argv[2]);
		exit(1);
	}

	releaseOutput(&outputState);

	array = parseManifest(manifest, &n);
	if (!array) {
		XLOG(0, "FATAL: cannot parse manifest\n");
		exit(1);
	}

	OPENSSL_add_all_algorithms_noconf();
	p = cerb;
	x0 = d2i_X509(NULL, &p, cerb_len);
	if (!x0) {
		XLOG(0, "FATAL: cannot load root CA\n");
		exit(1);
	}

	ticket = (DataValue *)getValueByKey(signDict, "APTicket");
	if (ticket) {
		p = ticket->value;
		rv = asn1_parse2(&p, ticket->len, 0, 0);
		if (!rv || !apcert.value || !rsasig.value || !theset.value) {
			XLOG(0, "FATAL: cannot parse ticket\n");
			exit(1);
		}
		if (clen > 0 && contarray->len == 8) {
			savecid = getECID(contarray->value);
		}
		if (!savecid) {
			printf("ERROR: bad, bad ECID\n");
			error = 1;
		}

		rv = extract2Certs(apcert.value, apcert.len, &y1, &y2);
		if (rv == 0) {
			rv = cryptoMagic(x0, y1, y2, theset.value, theset.len, (unsigned char *)rsasig.value, rsasig.len, NULL);
			X509_free(y1);
			X509_free(y2);
		}
		if (rv) {
			printf("ERROR: APTicket failed crypto\n");
			error = 1;
		}
	} else {
		VERBOSE("WARNING: cannot find ticket in %s\n", argv[1]);
	}

	dict = (Dictionary *)signDict->values;
	while (dict) {
		DataValue *blob = NULL;
		DataValue *partialDigest = NULL;
		if (dict->dValue.type == DictionaryType) {
			blob = (DataValue *)getValueByKey(dict, "Blob");
			partialDigest = (DataValue *)getValueByKey(dict, "PartialDigest");
		}
		if (blob && partialDigest) {
			const char *diag = checkBlob(x0, blob, partialDigest, &savecid);
			if (diag) {
				printf("ERROR: Blob for %s is invalid (%s)\n", dict->dValue.key, diag);
				error = 1;
			} else {
				for (i = 0; i < n; i++) {
					struct component_t *centry = array + i;
					if (centry->partial &&
					    partialDigest->len == centry->partial->len &&
					    !memcmp(partialDigest->value, centry->partial->value, partialDigest->len)) {
						array[i].blob = blob;
					}
				}
			}
		}
		dict = (Dictionary *)dict->dValue.next;
	}

	if (!ticket && !savecid) {
		printf("ERROR: bad, bad ECID\n");
		error = 1;
	}

	for (i = 0; i < n; i++) {
		struct component_t *centry = array + i;
		int found = FALSE;
		for (j = 0; j < clen; j++) {
			struct tuple_t *tentry = contarray + j;
			if (tentry->len == centry->digest->len && !memcmp(tentry->value, centry->digest->value, tentry->len)) {
				found = TRUE;
			}
		}
		if (!found) {
			if (centry->blob) {
				VERBOSE("WARNING: no digest for %s (%s), but it has blob\n", centry->key, centry->path);
			} else if (!centry->required) {
				VERBOSE("WARNING: no digest for %s (%s), but it is not critical\n", centry->key, centry->path);
			} else {
				printf("ERROR: no digest for %s (%s) and no blob found\n", centry->key, centry->path);
				error = 1;
			}
		} else {
			VERBOSE("INFO: %s (%s) is signed by APTicket%s\n", centry->key, centry->path, centry->blob ? " and blob" : "");
		}
	}
	free(array);
	free(contarray);

	releaseDictionary(manifest);
	releaseDictionary(signDict);

	if (error) {
		printf("%s is BROKEN\n", argv[1]);
	} else {
		printf("%s seems usable for ECID 0x%016llX\n", argv[1], savecid);
	}

	X509_free(x0);

	EVP_cleanup();
	ERR_remove_state(0);
	CRYPTO_cleanup_all_ex_data();
	return error;
}
示例#11
0
文件: server.c 项目: mrmign/armingDB
int handle_one_request(ServiceHandler h, char *buf, int buf_size)
{

    debug;
    char Buf[MAX_BUF_LEN] = "\0";
    int BufSize = MAX_BUF_LEN;
    char Data1[MAX_BUF_LEN] = "\0";
    char Data2[MAX_BUF_LEN] = "\0";

    mDataFormat data = (mDataFormat) malloc(sizeof(struct DataFormat));
    data->value1 = Data1;
    data->value2 = Data2;

    memset(Data1, 0, MAX_BUF_LEN);
    memset(Data2, 0, MAX_BUF_LEN);
    data->value1 = Data1;
    data->value2 = Data2;

    /*if(receive_data(h,Buf,&BufSize) == 0)
      {
          fprintf(stderr,"Connection Error,%s:%d\n",__FILE__,__LINE__);
          return -1;            
      }*/
    if(BufSize == 0)
    {
        free(data);
        return -1;
    }
    int ret = parse_data(buf,data);

    // print the received data
    // printRec(data);

    if(ret == -1)
    {
        error_response(h,"Data Format Error!\n");
        printf("server parse_data error!\n");
        free(data);
        return -1;
    }
    if(data->cmd == OPEN_CMD)
    {
        debug;
        Database db = createNewDB(data->value1);
        debug_argv("open db:%p\n",db);
        match_sockfd_mdb(h, db);
        BufSize = MAX_BUF_LEN;
        data->value_num = 0;
        BufSize = format_data(Buf,data);
        assert(BufSize > 0);
        send_data(h,Buf,BufSize);
    }
    else if(data->cmd == CLOSE_CMD)
    {
        debug_argv("close db\n");
        Database db = NULL;
        get_mdb(h, &db);
        closeDB(db);
        BufSize = MAX_BUF_LEN;
        data->value_num = 0;
        BufSize = format_data(Buf,data);
        send_data(h,Buf,BufSize);
        detach_sockfd_mdb(h);
        service_stop(h);
        free(data);
        return 0;
    }
    else if(data->cmd == GET_CMD)
    {
        Database db = NULL;
        get_mdb(h, &db);

        //debug_argv("get db:%p\n",db);
        int key = *(int *)data->value1;
        Data value;

        char tem[MAX_BUF_LEN] = "\0";
        value.value = tem;
        ret = getValueByKey(db, key, &value);
       // printf("server getdata value => %s\n", value.value);
        if(ret == -1)
        {
            error_response(h,"The key NOT FOUND!\n");
            free(data);
            return -1;              
        }
        BufSize = MAX_BUF_LEN;
        data->value_num = 1;
        data->len_value1 = strlen(value.value);
        data->value1 = value.value;
        BufSize = format_data(Buf,data);
        send_data(h,Buf,BufSize);

    }
    else if(data->cmd == SET_CMD)
    {
        int key = *(int *)data->value1;
        Data value;
        value.value = data->value2;
        value.length = data->len_value2;
        Database db = NULL;
        get_mdb(h, &db);
        debug_argv("set: db:%p\n",db);
        ret = putKeyValue(db,key,&value);
        if (ret == -1)
        {
            error_response(h,"Save key & value error!\n");
            printf("set error : %d, %s\n", key, value.value);
            free(data);
            return -1;
        }
        BufSize = MAX_BUF_LEN;
        data->value_num = 0;
        BufSize = format_data(Buf,data);
        send_data(h,Buf,BufSize);    

    }
    else if(data->cmd == DEL_CMD)
    {
        int key = *(int *)data->value1;;           
        Database db = NULL;
        get_mdb(h, &db);
        debug_argv("delete: db:%p\n",db);
        ret = deleteValueByKey(db,key);
        if(ret == -1)
        {
            error_response(h,"The key NOT FOUND!\n");
            free(data);
            return -1;
        }            
        BufSize = MAX_BUF_LEN;
        data->value_num = 0;
        BufSize = format_data(Buf,data);
        send_data(h,Buf,BufSize);             
    }
    else
    {
        printf("Unknow Request!\n");
        error_response(h, "Unknow Request!\n");
    }                                   
    free(data);
    return 0;
}
示例#12
0
文件: cgi.c 项目: yuruiz/Liso
static void buildEnvp(response_t* resp){
    char* uri = resp->uri;
    char *page_end = strchr(uri, '?');
    char *path_info = uri + strlen("/cgi");

    char* query = NULL;

    if (page_end != NULL) {
        *page_end = '\0';
        query = page_end + 1;
    }

    logging("Start inserting\n");
    insertEnvp(resp, "GATEWAY_INTERFACE", "CGI/1.1");
    insertEnvp(resp, "SERVER_PROTOCOL", "HTTP/1.1");
    insertEnvp(resp, "SERVER_SOFTWARE", "Liso/1.0");
    insertEnvp(resp, "SCRIPT_NAME", "/cgi");
//    logging("Static message inserting finished\n");

    insertEnvp(resp, "REQUEST_URI", resp->page);
    insertEnvp(resp, "QUERY_STRING", query);
    insertEnvp(resp, "PATH_INFO", path_info);
    insertEnvp(resp, "REQUEST_METHOD", methodtoString(resp->method));
//    logging("Query inserting finished\n");
    if (resp->ishttps) {
        insertEnvp(resp, "SERVER_PORT", _https_port);
        insertEnvp(resp, "HTTPS", "1");
    }
    else {
        insertEnvp(resp, "SERVER_PORT", _http_port);
        insertEnvp(resp, "HTTP", "1");
    }

    insertEnvp(resp, "REMOTE_ADDR", resp->addr);
    insertEnvp(resp, "CONTENT_LENGTH", getValueByKey(resp->hdhead, "Content-Length"));
    insertEnvp(resp, "CONTENT_TYPE", getValueByKey(resp->hdhead, "Content-Type"));
    insertEnvp(resp, "HTTP_ACCEPT", getValueByKey(resp->hdhead, "Accept"));
    insertEnvp(resp, "HTTP_REFERER", getValueByKey(resp->hdhead, "Referer"));
    insertEnvp(resp, "HTTP_ACCEPT_ENCODING", getValueByKey(resp->hdhead, "Accept-Encoding"));
    insertEnvp(resp, "HTTP_ACCEPT_LANGUAGE", getValueByKey(resp->hdhead, "Accept-Language"));
    insertEnvp(resp, "HTTP_ACCEPT_CHARSET", getValueByKey(resp->hdhead, "Accept-Charset"));
    insertEnvp(resp, "HTTP_HOST", getValueByKey(resp->hdhead, "Host"));
    insertEnvp(resp, "HTTP_COOKIE", getValueByKey(resp->hdhead, "Cookie"));
    insertEnvp(resp, "HTTP_USER_AGENT", getValueByKey(resp->hdhead, "User-Agent"));
    insertEnvp(resp, "HTTP_CONNECTION", getValueByKey(resp->hdhead, "Connection"));
    logging("Inserting Finished\n");

    return;

}