void AndroidFormat::updateSha1Hash(BootImageHeader *hdr)
{
    SHA_CTX ctx;
    SHA_init(&ctx);

    SHA_update(&ctx, mI10e->kernelImage.data(), mI10e->kernelImage.size());
    SHA_update(&ctx, reinterpret_cast<char *>(&hdr->kernel_size),
               sizeof(hdr->kernel_size));

    SHA_update(&ctx, mI10e->ramdiskImage.data(), mI10e->ramdiskImage.size());
    SHA_update(&ctx, reinterpret_cast<char *>(&hdr->ramdisk_size),
               sizeof(hdr->ramdisk_size));
    if (!mI10e->secondImage.empty()) {
        SHA_update(&ctx, mI10e->secondImage.data(), mI10e->secondImage.size());
    }

    // Bug in AOSP? AOSP's mkbootimg adds the second bootloader size to the SHA1
    // hash even if it's 0
    SHA_update(&ctx, reinterpret_cast<char *>(&hdr->second_size),
               sizeof(hdr->second_size));

    if (!mI10e->dtImage.empty()) {
        SHA_update(&ctx, mI10e->dtImage.data(), mI10e->dtImage.size());
        SHA_update(&ctx, reinterpret_cast<char *>(&hdr->dt_size),
                   sizeof(hdr->dt_size));
    }

    std::memset(hdr->id, 0, sizeof(hdr->id));
    memcpy(hdr->id, SHA_final(&ctx), SHA_DIGEST_SIZE);

    std::string hexDigest = StringUtils::toHex(
            reinterpret_cast<const unsigned char *>(hdr->id), SHA_DIGEST_SIZE);

    FLOGD("Computed new ID hash: %s", hexDigest.c_str());
}
示例#2
0
static bool SecureNSModeUbootImageShaCheck(second_loader_hdr *hdr)
{
#ifndef SECUREBOOT_CRYPTO_EN
	uint8_t *sha;
	SHA_CTX ctx;
	int size = SHA_DIGEST_SIZE > hdr->hash_len ? hdr->hash_len : SHA_DIGEST_SIZE;

	SHA_init(&ctx);
	SHA_update(&ctx, (void *)hdr + sizeof(second_loader_hdr), hdr->loader_load_size);
	SHA_update(&ctx, &hdr->loader_load_addr, sizeof(hdr->loader_load_addr));
	SHA_update(&ctx, &hdr->loader_load_size, sizeof(hdr->loader_load_size));
	SHA_update(&ctx, &hdr->hash_len, sizeof(hdr->hash_len));
	sha = SHA_final(&ctx);
#else
	uint32 size;
	uint8 *sha;
	uint32 hwDataHash[8];

	size = hdr->loader_load_size + sizeof(hdr->loader_load_size) \
		 + sizeof(hdr->loader_load_addr) + sizeof(hdr->hash_len);

	CryptoSHAInit(size, 160);
	/* rockchip's second level image. */
	CryptoSHAStart((uint32 *)((void *)hdr + sizeof(second_loader_hdr)), hdr->loader_load_size);
	CryptoSHAStart((uint32 *)&hdr->loader_load_addr, sizeof(hdr->loader_load_addr));
	CryptoSHAStart((uint32 *)&hdr->loader_load_size, sizeof(hdr->loader_load_size));
	CryptoSHAStart((uint32 *)&hdr->hash_len, sizeof(hdr->hash_len));

	CryptoSHAEnd(hwDataHash);

	sha = (uint8 *)hwDataHash;
	size = SHA_DIGEST_SIZE > hdr->hash_len ? hdr->hash_len : SHA_DIGEST_SIZE;
#endif

#if 0
	int i = 0;
	printf("\nreal sha:\n");
	for (i = 0;i < size;i++) {
		printf("%02x", (char)sha[i]);
	}
	printf("\nsha from image header:\n");
	for (i = 0;i < size;i++) {
		printf("%02x", ((char*)hdr->hash)[i]);
	}
	printf("\n");
#endif

	return !memcmp(hdr->hash, sha, size);
}
示例#3
0
文件: test.c 项目: quanium-89/sha
int main(int argc, char *argv[])
{
	SHA_CTX ctx;
	unsigned char buf[1024];
	unsigned char md[20];
	FILE *fp;
	int i, nread;

	fp = fopen(argv[1], "r");
	if (fp == NULL) {
		fprintf(stderr, "Open failed\n");
		exit(-1);
	}

	SHA_init(&ctx);
	while (!feof(fp)) {
		nread = fread(buf, 1, sizeof(buf), fp);
		SHA_update(&ctx, buf, nread);
	}
	SHA_final(md, &ctx);

	for (i = 0; i < 20; i++)
		printf("%02x", md[i]);
	printf("\n");

	return 0;
}
示例#4
0
// get hex sha
char * shaFile(const char * filename){
#define BUF_SHA 4096
    char buf[BUF_SHA];
    SHA_CTX sha_ctx;
    SHA_init(&sha_ctx);
    FILE * file = fopen(filename, "rb");

    if(file == NULL){
        fprintf(stderr, "can not open file %s for sha\n", filename);
        return NULL;
    }

    int read = 0;
    while( (read = fread(buf, 1, BUF_SHA, file) ) > 0){
        SHA_update(&sha_ctx, buf, read);
    }
    if(fclose(file))
        return NULL;
    const char * sha_final = (char *)SHA_final(&sha_ctx);
    
    if(sha_final == NULL) return NULL;

    char * hex = (char *)malloc(sizeof(char ) * (2 * SHA_DIGEST_SIZE + 1 ));

    if(!hex) return NULL;
    if(!hexSha1(sha_final, hex)) return hex;
    free(hex); hex=NULL;
    return NULL;
}
示例#5
0
/* Convenience function */
const uint8_t* SHA(const void* data, int len, uint8_t* digest) {
  SHA_CTX ctx;
  SHA_init(&ctx);
  SHA_update(&ctx, data, len);
  memcpy(digest, SHA_final(&ctx), SHA_DIGEST_SIZE);
  return digest;
}
示例#6
0
static void updateSha1Hash(BootImageHeader *hdr,
                           const BootImageIntermediate *i10e,
                           const MtkHeader *mtkKernelHdr,
                           const MtkHeader *mtkRamdiskHdr,
                           uint32_t kernelSize,
                           uint32_t ramdiskSize)
{
    SHA_CTX ctx;
    SHA_init(&ctx);

    if (mtkKernelHdr) {
        SHA_update(&ctx, mtkKernelHdr, sizeof(MtkHeader));
    }
    SHA_update(&ctx, i10e->kernelImage.data(), i10e->kernelImage.size());
    SHA_update(&ctx, reinterpret_cast<char *>(&kernelSize),
               sizeof(kernelSize));

    if (mtkRamdiskHdr) {
        SHA_update(&ctx, mtkRamdiskHdr, sizeof(MtkHeader));
    }
    SHA_update(&ctx, i10e->ramdiskImage.data(), i10e->ramdiskImage.size());
    SHA_update(&ctx, reinterpret_cast<char *>(&ramdiskSize),
               sizeof(ramdiskSize));
    if (!i10e->secondImage.empty()) {
        SHA_update(&ctx, i10e->secondImage.data(), i10e->secondImage.size());
    }

    // Bug in AOSP? AOSP's mkbootimg adds the second bootloader size to the SHA1
    // hash even if it's 0
    SHA_update(&ctx, reinterpret_cast<char *>(&hdr->second_size),
               sizeof(hdr->second_size));

    if (!i10e->dtImage.empty()) {
        SHA_update(&ctx, i10e->dtImage.data(), i10e->dtImage.size());
        SHA_update(&ctx, reinterpret_cast<char *>(&hdr->dt_size),
                   sizeof(hdr->dt_size));
    }

    std::memset(hdr->id, 0, sizeof(hdr->id));
    memcpy(hdr->id, SHA_final(&ctx), SHA_DIGEST_SIZE);

    std::string hexDigest = StringUtils::toHex(
            reinterpret_cast<const unsigned char *>(hdr->id), SHA_DIGEST_SIZE);

    LOGD("Computed new ID hash: %s", hexDigest.c_str());
}
示例#7
0
int sha_verify(FILE *f,  uint8_t*sha0, size_t signed_len)
{
	SHA_CTX ctx;
	SHA_init(&ctx);
	//FILE *f = fopen(name,"r");
	if(NULL==f){
		DEBUG("can not do sha verify with NULL file handle\n");
		return -1;
	}
	
	unsigned char* buffer = malloc(BUFFER_SIZE);
	if (NULL==buffer){
		DEBUG("failed to alloc memory for sha1 buffer\n");
		//fclose(f);
		return -1; //VERIFY_FAILURE;
	}
	
	double frac = -1.0;
	size_t so_far = 0;
	//   fseek(f, 0, SEEK_SET);
	while (so_far < signed_len) {
		size_t size = BUFFER_SIZE;
		if (signed_len - so_far < size)
			size = signed_len - so_far;
		if (fread(buffer, 1, size, f) != size) {
			DEBUG("failed to read data: %s\n", strerror(errno));
			//         fclose(f);
			free(buffer);
			buffer = NULL;
			return -1;//VERIFY_FAILURE;
		}
		SHA_update(&ctx, buffer, size);
		so_far += size;
		double df = so_far / (double)signed_len;
		if (df > frac + 0.02 || size == so_far) {
			frac = df;
		}
	}
	// fclose(f);
	free(buffer);
	
	const uint8_t* sha1 = SHA_final(&ctx);
	unsigned int i = 0;// = sizeof(sha1);
	printf("\n sha1 longth is [%d]\n",sizeof(ctx.buf));
	for(i=0; i<sizeof(ctx.buf); i++)
	{ 
		//printf("%.2x",ctx.buf[i]);   
		if(*sha1++ != *sha0++)
		{
			DEBUG("sha verify failed, not return when -1 currently\n");
			return -1;
		}
		else
			DEBUG("sha verify success\n");
	}
	printf("\n");
	return 0;
}
示例#8
0
文件: sha.c 项目: zt515/c4pkg
const uint8_t* SHA_final(SHA_CTX* ctx) {
    uint64_t cnt = ctx->count * 8;
    int i;

    SHA_update(ctx, (uint8_t*)"\x80", 1);
    while ((ctx->count % sizeof(ctx->buf)) != (sizeof(ctx->buf) - 8)) {
        SHA_update(ctx, (uint8_t*)"\0", 1);
    }
    for (i = 0; i < 8; ++i) {
        uint8_t tmp = cnt >> ((7 - i) * 8);
        SHA_update(ctx, &tmp, 1);
    }

    for (i = 0; i < 5; i++) {
        ctx->buf.w[i] = bswap_32(ctx->state[i]);
    }

    return ctx->buf.b;
}
示例#9
0
文件: sha.c 项目: mq002/miqi-uboot
static void blk_SHA1_Final(unsigned char hashout[20], SHA_CTX *ctx)
{
	static const unsigned char pad[64] = { 0x80 };
	unsigned int padlen[2];
	int i;
	uint32_t tmp;

	/* Pad with a binary 1 (ie 0x80), then zeroes, then length */
	tmp = (uint32_t)(ctx->size >> 29);
	padlen[0] = get_be32(&tmp);
	tmp = (uint32_t)(ctx->size << 3);
	padlen[1] = get_be32(&tmp);

	i = ctx->size & 63;
	SHA_update(ctx, pad, 1+ (63 & (55 - i)));
	SHA_update(ctx, padlen, 8);

	/* Output hash */
	for (i = 0; i < 5; i++)
		put_be32(hashout + i*4, ctx->H[i]);
}
示例#10
0
文件: sha.c 项目: zt515/c4pkg
/* Convenience function */
const uint8_t* SHA_hash(const void *data, int len, uint8_t *digest) {
    const uint8_t *p;
    int i;
    SHA_CTX ctx;
    SHA_init(&ctx);
    SHA_update(&ctx, data, len);
    p = SHA_final(&ctx);
    for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
        digest[i] = *p++;
    }
    return digest;
}
示例#11
0
Value* RangeSha1Fn(const char* name, State* state, int argc, Expr* argv[]) {
    Value* blockdev_filename;
    Value* ranges;
    const uint8_t* digest = NULL;
    if (ReadValueArgs(state, argv, 2, &blockdev_filename, &ranges) < 0) {
        return NULL;
    }

    if (blockdev_filename->type != VAL_STRING) {
        ErrorAbort(state, "blockdev_filename argument to %s must be string", name);
        goto done;
    }
    if (ranges->type != VAL_STRING) {
        ErrorAbort(state, "ranges argument to %s must be string", name);
        goto done;
    }

    int fd = open(blockdev_filename->data, O_RDWR);
    if (fd < 0) {
        ErrorAbort(state, "failed to open %s: %s", blockdev_filename->data, strerror(errno));
        goto done;
    }

    RangeSet* rs = parse_range(ranges->data);
    uint8_t buffer[BLOCKSIZE];

    SHA_CTX ctx;
    SHA_init(&ctx);

    int i, j;
    for (i = 0; i < rs->count; ++i) {
        check_lseek(fd, (off64_t)rs->pos[i*2] * BLOCKSIZE, SEEK_SET);
        for (j = rs->pos[i*2]; j < rs->pos[i*2+1]; ++j) {
            readblock(fd, buffer, BLOCKSIZE);
            SHA_update(&ctx, buffer, BLOCKSIZE);
        }
    }
    digest = SHA_final(&ctx);
    close(fd);

  done:
    FreeValue(blockdev_filename);
    FreeValue(ranges);
    if (digest == NULL) {
        return StringValue(strdup(""));
    } else {
        return StringValue(PrintSha1(digest));
    }
}
示例#12
0
int DxCore::sub_12FC(void *buf, int len, void *dest) {
	SHA_CTX ctx;
	SHA_init(&ctx);
	int left = len;
	int pos = 0;

	while (left > 0) {
		SHA_update(&ctx, (u8 *) buf + pos, left > 4096 ? 4096 : left);
		left -= 4096;
		pos += 4096;
	}
	const u8* ret = SHA_final(&ctx);
	memcpy(dest, ret, UUID_LEN);
	return 0;
}
示例#13
0
文件: sha.c 项目: zt515/c4pkg
const uint8_t *SHA_final(SHA_CTX *ctx) {
    uint8_t *p = ctx->buf;
    uint64_t cnt = ctx->count * 8;
    int i;

    SHA_update(ctx, (uint8_t*)"\x80", 1);
    while ((ctx->count % sizeof(ctx->buf)) != (sizeof(ctx->buf) - 8)) {
        SHA_update(ctx, (uint8_t*)"\0", 1);
    }
    for (i = 0; i < 8; ++i) {
        uint8_t tmp = cnt >> ((7 - i) * 8);
        SHA_update(ctx, &tmp, 1);
    }

    for (i = 0; i < 5; i++) {
        uint32_t tmp = ctx->state[i];
        *p++ = tmp >> 24;
        *p++ = tmp >> 16;
        *p++ = tmp >> 8;
        *p++ = tmp >> 0;
    }

    return ctx->buf;
}
示例#14
0
int DxCore::sub_1370(const char *filepath, void *dest) {
	FILE *fp = fopen(filepath, "rb");
	if (fp == NULL) {
		return -1;
	}

	SHA_CTX ctx;
	u8 buf[4096];
	int n = -1;
	SHA_init(&ctx);
	while ((n = fread(buf, 1, 4096, fp)) > 0) {
		SHA_update(&ctx, buf, n);
	}
	fclose(fp);
	const u8* ret = SHA_final(&ctx);
	memcpy(dest, ret, UUID_LEN);
	return 0;
}
示例#15
0
int ApplyBSDiffPatch(const unsigned char* old_data, ssize_t old_size,
                     const Value* patch, ssize_t patch_offset,
                     SinkFn sink, void* token, SHA_CTX* ctx) {

    unsigned char* new_data;
    ssize_t new_size;
    if (ApplyBSDiffPatchMem(old_data, old_size, patch, patch_offset,
                            &new_data, &new_size) != 0) {
        return -1;
    }

    if (sink(new_data, new_size, token) < new_size) {
        printf("short write of output: %d (%s)\n", errno, strerror(errno));
        return 1;
    }
    if (ctx) SHA_update(ctx, new_data, new_size);
    free(new_data);

    return 0;
}
示例#16
0
文件: fmap.c 项目: Tydus/flashmap
/* get SHA1 sum of all static regions described by the flashmap and copy into
   *digest (which will be allocated and must be freed by the caller),  */
int fmap_get_csum(const uint8_t *image, unsigned int image_len, uint8_t **digest)
{
	int i;
	struct fmap *fmap;
	int fmap_offset;
	SHA_CTX ctx;

	if ((image == NULL))
		return -1;

	if ((fmap_offset = fmap_find(image, image_len)) < 0)
		return -1;
	fmap = (struct fmap *)(image + fmap_offset);

	SHA_init(&ctx);

	/* Iterate through flash map and calculate the checksum piece-wise. */
	for (i = 0; i < fmap->nareas; i++) {
		/* skip non-static areas */
		if (!(fmap->areas[i].flags & FMAP_AREA_STATIC))
			continue;

		/* sanity check the offset */
		if (fmap->areas[i].size + fmap->areas[i].offset > image_len) {
			fprintf(stderr,
			        "(%s) invalid parameter detected in area %d\n",
			        __func__, i);
			return -1;
		}

		SHA_update(&ctx,
		           image + fmap->areas[i].offset,
		           fmap->areas[i].size);
	}

	SHA_final(&ctx);
	*digest = malloc(SHA_DIGEST_SIZE);
	memcpy(*digest, ctx.buf, SHA_DIGEST_SIZE);

	return SHA_DIGEST_SIZE;
}
char *
util_hash_sha_image_file_new(const char *image_file)
{
	FILE *fp = NULL;
	SHA_CTX ctx;
	SHA_init(&ctx);

	if (!(fp = fopen(image_file, "rb"))) {
		ERROR_ERRNO("Error in file hasing, cannot open %s", image_file);
		return NULL;
	}

	int len = 0;
	unsigned char buf[SIGN_HASH_BUFFER_SIZE];

	while ((len = fread(buf, 1, sizeof(buf), fp)) > 0) {
		SHA_update(&ctx, buf, len);
	}
	fclose(fp);

	return convert_bin_to_hex_new(SHA_final(&ctx), SHA_DIGEST_SIZE);
}
示例#18
0
int verify_file(const char* path, const RSAPublicKey *pKeys, unsigned int numKeys) {
    ui->SetProgress(0.0);

    FILE* f = fopen(path, "rb");
    if (f == NULL) {
        LOGE("failed to open %s (%s)\n", path, strerror(errno));
        return VERIFY_FAILURE;
    }

    // An archive with a whole-file signature will end in six bytes:
    //
    //   (2-byte signature start) $ff $ff (2-byte comment size)
    //
    // (As far as the ZIP format is concerned, these are part of the
    // archive comment.)  We start by reading this footer, this tells
    // us how far back from the end we have to start reading to find
    // the whole comment.

#define FOOTER_SIZE 6

    if (fseek(f, -FOOTER_SIZE, SEEK_END) != 0) {
        LOGE("failed to seek in %s (%s)\n", path, strerror(errno));
        fclose(f);
        return VERIFY_FAILURE;
    }

    unsigned char footer[FOOTER_SIZE];
    if (fread(footer, 1, FOOTER_SIZE, f) != FOOTER_SIZE) {
        LOGE("failed to read footer from %s (%s)\n", path, strerror(errno));
        fclose(f);
        return VERIFY_FAILURE;
    }

    if (footer[2] != 0xff || footer[3] != 0xff) {
        fclose(f);
        return VERIFY_FAILURE;
    }

    size_t comment_size = footer[4] + (footer[5] << 8);
    size_t signature_start = footer[0] + (footer[1] << 8);
    LOGI("comment is %d bytes; signature %d bytes from end\n",
         comment_size, signature_start);

    if (signature_start - FOOTER_SIZE < RSANUMBYTES) {
        // "signature" block isn't big enough to contain an RSA block.
        LOGE("signature is too short\n");
        fclose(f);
        return VERIFY_FAILURE;
    }

#define EOCD_HEADER_SIZE 22

    // The end-of-central-directory record is 22 bytes plus any
    // comment length.
    size_t eocd_size = comment_size + EOCD_HEADER_SIZE;

    if (fseek(f, -eocd_size, SEEK_END) != 0) {
        LOGE("failed to seek in %s (%s)\n", path, strerror(errno));
        fclose(f);
        return VERIFY_FAILURE;
    }

    // Determine how much of the file is covered by the signature.
    // This is everything except the signature data and length, which
    // includes all of the EOCD except for the comment length field (2
    // bytes) and the comment data.
    size_t signed_len = ftell(f) + EOCD_HEADER_SIZE - 2;

    unsigned char* eocd = (unsigned char*)malloc(eocd_size);
    if (eocd == NULL) {
        LOGE("malloc for EOCD record failed\n");
        fclose(f);
        return VERIFY_FAILURE;
    }
    if (fread(eocd, 1, eocd_size, f) != eocd_size) {
        LOGE("failed to read eocd from %s (%s)\n", path, strerror(errno));
        fclose(f);
        return VERIFY_FAILURE;
    }

    // If this is really is the EOCD record, it will begin with the
    // magic number $50 $4b $05 $06.
    if (eocd[0] != 0x50 || eocd[1] != 0x4b ||
        eocd[2] != 0x05 || eocd[3] != 0x06) {
        LOGE("signature length doesn't match EOCD marker\n");
        fclose(f);
        return VERIFY_FAILURE;
    }

    size_t i;
    for (i = 4; i < eocd_size-3; ++i) {
        if (eocd[i  ] == 0x50 && eocd[i+1] == 0x4b &&
            eocd[i+2] == 0x05 && eocd[i+3] == 0x06) {
            // if the sequence $50 $4b $05 $06 appears anywhere after
            // the real one, minzip will find the later (wrong) one,
            // which could be exploitable.  Fail verification if
            // this sequence occurs anywhere after the real one.
            LOGE("EOCD marker occurs after start of EOCD\n");
            fclose(f);
            return VERIFY_FAILURE;
        }
    }

#define BUFFER_SIZE 4096

    SHA_CTX ctx;
    SHA_init(&ctx);
    unsigned char* buffer = (unsigned char*)malloc(BUFFER_SIZE);
    if (buffer == NULL) {
        LOGE("failed to alloc memory for sha1 buffer\n");
        fclose(f);
        return VERIFY_FAILURE;
    }

    double frac = -1.0;
    size_t so_far = 0;
    fseek(f, 0, SEEK_SET);
    while (so_far < signed_len) {
        size_t size = BUFFER_SIZE;
        if (signed_len - so_far < size) size = signed_len - so_far;
        if (fread(buffer, 1, size, f) != size) {
            LOGE("failed to read data from %s (%s)\n", path, strerror(errno));
            fclose(f);
            return VERIFY_FAILURE;
        }
        SHA_update(&ctx, buffer, size);
        so_far += size;
        double f = so_far / (double)signed_len;
        if (f > frac + 0.02 || size == so_far) {
            ui->SetProgress(f);
            frac = f;
        }
    }
    fclose(f);
    free(buffer);

    const uint8_t* sha1 = SHA_final(&ctx);
    for (i = 0; i < numKeys; ++i) {
        // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that
        // the signing tool appends after the signature itself.
        if (RSA_verify(pKeys+i, eocd + eocd_size - 6 - RSANUMBYTES,
                       RSANUMBYTES, sha1)) {
            LOGI("whole-file signature verified against key %d\n", i);
            free(eocd);
            return VERIFY_SUCCESS;
        } else {
            LOGI("failed to verify against key %d\n", i);
        }
    }
    free(eocd);
    LOGE("failed to verify whole-file signature\n");
    return VERIFY_FAILURE;
}
示例#19
0
static int LoadPartitionContents(const char* filename, FileContents* file) {
    char* copy = strdup(filename);
    const char* magic = strtok(copy, ":");

    enum PartitionType type;

#if 0 //wschen 2012-05-24
    if (strcmp(magic, "MTD") == 0) {
        type = MTD;
    } else if (strcmp(magic, "EMMC") == 0) {
        type = EMMC;
    } else {
        printf("LoadPartitionContents called with bad filename (%s)\n",
               filename);
        return -1;
    }
#else

    switch (phone_type()) {
        case NAND_TYPE:
            type = MTD;
            break;
        case EMMC_TYPE:
            type = EMMC;
            break;
        default:
            printf("LoadPartitionContents called with bad filename (%s)\n", filename);
            return -1;
    }
#endif

    const char* partition = strtok(NULL, ":");

    int i;
    int colons = 0;
    for (i = 0; filename[i] != '\0'; ++i) {
        if (filename[i] == ':') {
            ++colons;
        }
    }
    if (colons < 3 || colons%2 == 0) {
        printf("LoadPartitionContents called with bad filename (%s)\n",
               filename);
    }

    int pairs = (colons-1)/2;     // # of (size,sha1) pairs in filename
    int* index = malloc(pairs * sizeof(int));
    size_t* size = malloc(pairs * sizeof(size_t));
    char** sha1sum = malloc(pairs * sizeof(char*));

    for (i = 0; i < pairs; ++i) {
        const char* size_str = strtok(NULL, ":");
        size[i] = strtol(size_str, NULL, 10);
        if (size[i] == 0) {
            printf("LoadPartitionContents called with bad size (%s)\n", filename);
            return -1;
        }
        sha1sum[i] = strtok(NULL, ":");
        index[i] = i;
    }

    // sort the index[] array so it indexes the pairs in order of
    // increasing size.
    size_array = size;
    qsort(index, pairs, sizeof(int), compare_size_indices);

    MtdReadContext* ctx = NULL;
    int dev = -1;

    switch (type) {
        case MTD:
            if (!mtd_partitions_scanned) {
                mtd_scan_partitions();
                mtd_partitions_scanned = 1;
            }

            const MtdPartition* mtd = mtd_find_partition_by_name(partition);
            if (mtd == NULL) {
                printf("mtd partition \"%s\" not found (loading %s)\n",
                       partition, filename);
                return -1;
            }

            ctx = mtd_read_partition(mtd);
            if (ctx == NULL) {
                printf("failed to initialize read of mtd partition \"%s\"\n",
                       partition);
                return -1;
            }
            break;

        case EMMC:
            printf("open emmc partition \"%s\"\n", partition);
            if (!strcmp(partition, "boot")) {
                dev = open("/dev/bootimg", O_RDWR);
                if (dev == -1) {
                    printf("failed to open emmc partition \"/dev/bootimg\": %s\n", strerror(errno));
                    return -1;
                }
            } else {
                char dev_name[32];

                strcpy(dev_name, "/dev/");
                strcat(dev_name, partition);
                dev = open(dev_name, O_RDWR);
                if (dev == -1) {
                    printf("failed to open emmc partition \"%s\": %s\n",
                           dev_name, strerror(errno));
                    return -1;
                }
            }
            break;
    }

    SHA_CTX sha_ctx;
    SHA_init(&sha_ctx);
    uint8_t parsed_sha[SHA_DIGEST_SIZE];

    // allocate enough memory to hold the largest size.
    file->data = malloc(size[index[pairs-1]]);
    char* p = (char*)file->data;
    file->size = 0;                // # bytes read so far

    for (i = 0; i < pairs; ++i) {
        // Read enough additional bytes to get us up to the next size
        // (again, we're trying the possibilities in order of increasing
        // size).
        size_t next = size[index[i]] - file->size;
        size_t read_cnt = 0;
        if (next > 0) {
            switch (type) {
                case MTD:
                    read_cnt = mtd_read_data(ctx, p, next);
                    break;

                case EMMC:
                    read_cnt = read(dev, p, next);
                    break;
            }
            if (next != read_cnt) {
                printf("short read (%d bytes of %d) for partition \"%s\"\n",
                       read_cnt, next, partition);
                free(file->data);
                file->data = NULL;
                return -1;
            }
            SHA_update(&sha_ctx, p, read_cnt);
            file->size += read_cnt;
        }

        // Duplicate the SHA context and finalize the duplicate so we can
        // check it against this pair's expected hash.
        SHA_CTX temp_ctx;
        memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
        const uint8_t* sha_so_far = SHA_final(&temp_ctx);

        if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
            printf("failed to parse sha1 %s in %s\n",
                   sha1sum[index[i]], filename);
            free(file->data);
            file->data = NULL;
            return -1;
        }

        if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_SIZE) == 0) {
            // we have a match.  stop reading the partition; we'll return
            // the data we've read so far.
            printf("partition read matched size %d sha %s\n",
                   size[index[i]], sha1sum[index[i]]);
            break;
        }

        p += read_cnt;
    }

    switch (type) {
        case MTD:
            mtd_read_close(ctx);
            break;

        case EMMC:
            close(dev);
            break;
    }


    if (i == pairs) {
        // Ran off the end of the list of (size,sha1) pairs without
        // finding a match.
        printf("contents of partition \"%s\" didn't match %s\n",
               partition, filename);
        free(file->data);
        file->data = NULL;
        return -1;
    }

    const uint8_t* sha_final = SHA_final(&sha_ctx);
    for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
        file->sha1[i] = sha_final[i];
    }

    // Fake some stat() info.
    file->st.st_mode = 0644;
    file->st.st_uid = 0;
    file->st.st_gid = 0;

    free(copy);
    free(index);
    free(size);
    free(sha1sum);

    return 0;
}
static int LoadPartitionContents(const char* filename, FileContents* file) {
    std::string copy(filename);
    std::vector<std::string> pieces = android::base::Split(copy, ":");
    if (pieces.size() < 4 || pieces.size() % 2 != 0) {
        printf("LoadPartitionContents called with bad filename (%s)\n", filename);
        return -1;
    }

    enum PartitionType type;
    if (pieces[0] == "MTD") {
        type = MTD;
    } else if (pieces[0] == "EMMC") {
        type = EMMC;
    } else {
        printf("LoadPartitionContents called with bad filename (%s)\n", filename);
        return -1;
    }
    const char* partition = pieces[1].c_str();

    size_t pairs = (pieces.size() - 2) / 2;    // # of (size, sha1) pairs in filename
    std::vector<size_t> index(pairs);
    std::vector<size_t> size(pairs);
    std::vector<std::string> sha1sum(pairs);

    for (size_t i = 0; i < pairs; ++i) {
        size[i] = strtol(pieces[i*2+2].c_str(), NULL, 10);
        if (size[i] == 0) {
            printf("LoadPartitionContents called with bad size (%s)\n", filename);
            return -1;
        }
        sha1sum[i] = pieces[i*2+3].c_str();
        index[i] = i;
    }

    // Sort the index[] array so it indexes the pairs in order of increasing size.
    sort(index.begin(), index.end(),
        [&](const size_t& i, const size_t& j) {
            return (size[i] < size[j]);
        }
    );

    MtdReadContext* ctx = NULL;
    FILE* dev = NULL;

    switch (type) {
        case MTD: {
            if (!mtd_partitions_scanned) {
                mtd_scan_partitions();
                mtd_partitions_scanned = true;
            }

            const MtdPartition* mtd = mtd_find_partition_by_name(partition);
            if (mtd == NULL) {
                printf("mtd partition \"%s\" not found (loading %s)\n", partition, filename);
                return -1;
            }

            ctx = mtd_read_partition(mtd);
            if (ctx == NULL) {
                printf("failed to initialize read of mtd partition \"%s\"\n", partition);
                return -1;
            }
            break;
        }

        case EMMC:
            dev = fopen(partition, "rb");
            if (dev == NULL) {
                printf("failed to open emmc partition \"%s\": %s\n", partition, strerror(errno));
                return -1;
            }
    }

    SHA_CTX sha_ctx;
    SHA_init(&sha_ctx);
    uint8_t parsed_sha[SHA_DIGEST_SIZE];

    // Allocate enough memory to hold the largest size.
    file->data = reinterpret_cast<unsigned char*>(malloc(size[index[pairs-1]]));
    char* p = (char*)file->data;
    file->size = 0;                // # bytes read so far
    bool found = false;

    for (size_t i = 0; i < pairs; ++i) {
        // Read enough additional bytes to get us up to the next size. (Again,
        // we're trying the possibilities in order of increasing size).
        size_t next = size[index[i]] - file->size;
        size_t read = 0;
        if (next > 0) {
            switch (type) {
                case MTD:
                    read = mtd_read_data(ctx, p, next);
                    break;

                case EMMC:
                    read = fread(p, 1, next, dev);
                    break;
            }
            if (next != read) {
                printf("short read (%zu bytes of %zu) for partition \"%s\"\n",
                       read, next, partition);
                free(file->data);
                file->data = NULL;
                return -1;
            }
            SHA_update(&sha_ctx, p, read);
            file->size += read;
        }

        // Duplicate the SHA context and finalize the duplicate so we can
        // check it against this pair's expected hash.
        SHA_CTX temp_ctx;
        memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
        const uint8_t* sha_so_far = SHA_final(&temp_ctx);

        if (ParseSha1(sha1sum[index[i]].c_str(), parsed_sha) != 0) {
            printf("failed to parse sha1 %s in %s\n", sha1sum[index[i]].c_str(), filename);
            free(file->data);
            file->data = NULL;
            return -1;
        }

        if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_SIZE) == 0) {
            // we have a match.  stop reading the partition; we'll return
            // the data we've read so far.
            printf("partition read matched size %zu sha %s\n",
                   size[index[i]], sha1sum[index[i]].c_str());
            found = true;
            break;
        }

        p += read;
    }

    switch (type) {
        case MTD:
            mtd_read_close(ctx);
            break;

        case EMMC:
            fclose(dev);
            break;
    }


    if (!found) {
        // Ran off the end of the list of (size,sha1) pairs without finding a match.
        printf("contents of partition \"%s\" didn't match %s\n", partition, filename);
        free(file->data);
        file->data = NULL;
        return -1;
    }

    const uint8_t* sha_final = SHA_final(&sha_ctx);
    for (size_t i = 0; i < SHA_DIGEST_SIZE; ++i) {
        file->sha1[i] = sha_final[i];
    }

    // Fake some stat() info.
    file->st.st_mode = 0644;
    file->st.st_uid = 0;
    file->st.st_gid = 0;

    return 0;
}
示例#21
0
static bool SecureRKModeVerifyBootImage(rk_boot_img_hdr *boothdr)
{
	int i;
	uint32 size;
	uint8 *dataHash;
	uint32 rsaResult[8];
	uint32 hwDataHash[8];
	uint8 *rsahash = (uint8 *)rsaResult;
	BOOT_HEADER *pkeyHead = (BOOT_HEADER *)g_rsa_key_buf;

#if 0
{
	int k = 0;
	char *buf = boothdr->id;

	printf("Boot Image Head: magic = %s, sign tag = 0x%x\n", boothdr->magic, boothdr->signTag);

	printf("Boot Image Head: hash data:\n");
	for (k = 0; k < sizeof(boothdr->id); k++) {
		printf("%02x", buf[k]);
	}
	printf("\n");

	printf("kernel addr = 0x%x, size = 0x%x\n", boothdr->kernel_addr, boothdr->kernel_size);
	printf("ramdisk addr = 0x%x, size = 0x%x\n", boothdr->ramdisk_addr, boothdr->ramdisk_size);
	printf("second addr = 0x%x, size = 0x%x\n", boothdr->second_addr, boothdr->second_size);
}
#endif

	/* verify boot/recovery image */
	if (memcmp(boothdr->magic, BOOT_MAGIC, BOOT_MAGIC_SIZE) != 0) {
		return false;
	}

	if (boothdr->signTag != SECURE_BOOT_SIGN_TAG) {
		return false;
	}
#if 0
{
	SHA_CTX ctx;

	SHA_init(&ctx);

	/* Android image */
	SHA_update(&ctx, (void *)boothdr->kernel_addr, boothdr->kernel_size);
	SHA_update(&ctx, &boothdr->kernel_size, sizeof(boothdr->kernel_size));
	SHA_update(&ctx, (void *)boothdr->ramdisk_addr, boothdr->ramdisk_size);
	SHA_update(&ctx, &boothdr->ramdisk_size, sizeof(boothdr->ramdisk_size));
	SHA_update(&ctx, (void *)boothdr->second_addr, boothdr->second_size);
	SHA_update(&ctx, &boothdr->second_size, sizeof(boothdr->second_size));

	/* rockchip's image add information. */
	SHA_update(&ctx, &boothdr->tags_addr, sizeof(boothdr->tags_addr));
	SHA_update(&ctx, &boothdr->page_size, sizeof(boothdr->page_size));
	SHA_update(&ctx, &boothdr->unused, sizeof(boothdr->unused));
	SHA_update(&ctx, &boothdr->name, sizeof(boothdr->name));
	SHA_update(&ctx, &boothdr->cmdline, sizeof(boothdr->cmdline));

	dataHash = SHA_final(&ctx);

	int k = 0;
	char *buf = dataHash;

	printf("Soft Calc Image hash data:\n");
	for (k = 0; k < sizeof(boothdr->id); k++) {
		printf("%02x", buf[k]);
	}
	printf("\n");
}
#endif

	size = boothdr->kernel_size + sizeof(boothdr->kernel_size) \
		+ boothdr->ramdisk_size + sizeof(boothdr->ramdisk_size) \
		+ boothdr->second_size + sizeof(boothdr->second_size) \
		+ sizeof(boothdr->tags_addr) + sizeof(boothdr->page_size) \
		+ sizeof(boothdr->unused) + sizeof(boothdr->name) + sizeof(boothdr->cmdline);

	CryptoRSAInit((uint32*)(boothdr->rsaHash), pkeyHead->RSA_N, pkeyHead->RSA_E, pkeyHead->RSA_C);
	CryptoSHAInit(size, 160);

	/* Android image. */
	CryptoSHAStart((uint32 *)(unsigned long)boothdr->kernel_addr, boothdr->kernel_size);
	CryptoSHAStart((uint32 *)&boothdr->kernel_size, sizeof(boothdr->kernel_size));
	CryptoSHAStart((uint32 *)(unsigned long)boothdr->ramdisk_addr, boothdr->ramdisk_size);
	CryptoSHAStart((uint32 *)&boothdr->ramdisk_size, sizeof(boothdr->ramdisk_size));
	CryptoSHAStart((uint32 *)(unsigned long)boothdr->second_addr, boothdr->second_size);
	CryptoSHAStart((uint32 *)&boothdr->second_size, sizeof(boothdr->second_size));

	/* only rockchip's image add. */
	CryptoSHAStart((uint32 *)&boothdr->tags_addr, sizeof(boothdr->tags_addr));
	CryptoSHAStart((uint32 *)&boothdr->page_size, sizeof(boothdr->page_size));
	CryptoSHAStart((uint32 *)&boothdr->unused, sizeof(boothdr->unused));
	CryptoSHAStart((uint32 *)&boothdr->name, sizeof(boothdr->name));
	CryptoSHAStart((uint32 *)&boothdr->cmdline, sizeof(boothdr->cmdline));

	CryptoSHAEnd(hwDataHash);
	CryptoRSAEnd(rsaResult);

	dataHash = (uint8 *)hwDataHash;

#if 0
{
	int k = 0;
	char *buf = dataHash;

	printf("Crypto Calc Image hash data:\n");
	for (k = 0; k < sizeof(boothdr->id); k++) {
		printf("%02x", buf[k]);
	}
	printf("\n");
}
#endif

	/* check the hash of image */
	if (memcmp(boothdr->id, hwDataHash, sizeof(boothdr->id)) != 0) {
		return false;
	}

	/* check the sign of hash */
	for (i = 0; i < 20; i++) {
		if (rsahash[19-i] != dataHash[i]) {
			return false;
		}
	}

	return true;
}
示例#22
0
int main(int argc, char **argv)
{
    boot_img_hdr hdr;

    char *kernel_fn = 0;
    void *kernel_data = 0;
    char *ramdisk_fn = 0;
    void *ramdisk_data = 0;
    char *second_fn = 0;
    void *second_data = 0;
    char *cmdline = "";
    char *bootimg = 0;
    char *board = "";
    unsigned pagesize = 2048;
    unsigned saddr = 0;
    int fd;
    SHA_CTX ctx;
    uint8_t* sha;

    argc--;
    argv++;

    memset(&hdr, 0, sizeof(hdr));

        /* default load addresses */
    hdr.kernel_addr =  0x10008000;
    hdr.ramdisk_addr = 0x11000000;
    hdr.second_addr =  0x10F00000;
    hdr.tags_addr =    0x10000100;

    hdr.page_size = pagesize;

    while(argc > 0){
        char *arg = argv[0];
        char *val = argv[1];
        if(argc < 2) {
            return usage();
        }
        argc -= 2;
        argv += 2;
        if(!strcmp(arg, "--output") || !strcmp(arg, "-o")) {
            bootimg = val;
        } else if(!strcmp(arg, "--kernel")) {
            kernel_fn = val;
        } else if(!strcmp(arg, "--ramdisk")) {
            ramdisk_fn = val;
        } else if(!strcmp(arg, "--second")) {
            second_fn = val;
        } else if(!strcmp(arg, "--cmdline")) {
            cmdline = val;
        } else if(!strcmp(arg, "--base")) {
            unsigned base = strtoul(val, 0, 16);
            hdr.kernel_addr =  base + 0x00008000;
            hdr.ramdisk_addr = base + 0x01000000;
            hdr.second_addr =  base + 0x00F00000;
            hdr.tags_addr =    base + 0x00000100;
        } else if(!strcmp(arg, "--board")) {
            board = val;
        } else {
            return usage();
        }
    }

    if(bootimg == 0) {
        fprintf(stderr,"error: no output filename specified\n");
        return usage();
    }

    if(kernel_fn == 0) {
        fprintf(stderr,"error: no kernel image specified\n");
        return usage();
    }

    if(ramdisk_fn == 0) {
        fprintf(stderr,"error: no ramdisk image specified\n");
        return usage();
    }

    if(strlen(board) >= BOOT_NAME_SIZE) {
        fprintf(stderr,"error: board name too large\n");
        return usage();
    }

    strcpy(hdr.name, board);

#ifndef GENERIC
    hdr.kernel_addr =  KERNEL_ADDR;
    hdr.ramdisk_addr = RAMDISK_ADDR;
    if(saddr) {
        hdr.second_addr =  0x00300000;
    } else {
        hdr.second_addr =  SECONDARY_ADDR;
    }
    hdr.tags_addr   =  TAGS_ADDR;
    hdr.page_size = pagesize;
#else
    hdr.kernel_addr =  0x208000;
    hdr.ramdisk_addr = 0x1200000;
    if(saddr) {
        hdr.second_addr =  0x00300000;
    } else {
        hdr.second_addr =  0x1100000;
    }
    hdr.tags_addr   =  0x10000100;
    hdr.page_size = pagesize;
#endif

    memcpy(hdr.magic, BOOT_MAGIC, BOOT_MAGIC_SIZE);

    if(strlen(cmdline) > (BOOT_ARGS_SIZE - 1)) {
        fprintf(stderr,"error: kernel commandline too large\n");
        return 1;
    }
    strcpy((char*)hdr.cmdline, cmdline);

    kernel_data = load_file(kernel_fn, &hdr.kernel_size);
    if(kernel_data == 0) {
        fprintf(stderr,"error: could not load kernel '%s'\n", kernel_fn);
        return 1;
    }

    if(!strcmp(ramdisk_fn,"NONE")) {
        ramdisk_data = 0;
        hdr.ramdisk_size = 0;
    } else {
        ramdisk_data = load_file(ramdisk_fn, &hdr.ramdisk_size);
        if(ramdisk_data == 0) {
            fprintf(stderr,"error: could not load ramdisk '%s'\n", ramdisk_fn);
            return 1;
        }
    }

    if(second_fn) {
        second_data = load_file(second_fn, &hdr.second_size);
        if(second_data == 0) {
            fprintf(stderr,"error: could not load secondstage '%s'\n", second_fn);
            return 1;
        }
    }

    /* put a hash of the contents in the header so boot images can be
     * differentiated based on their first 2k.
     */
    SHA_init(&ctx);
    SHA_update(&ctx, kernel_data, hdr.kernel_size);
    SHA_update(&ctx, &hdr.kernel_size, sizeof(hdr.kernel_size));
    SHA_update(&ctx, ramdisk_data, hdr.ramdisk_size);
    SHA_update(&ctx, &hdr.ramdisk_size, sizeof(hdr.ramdisk_size));
    SHA_update(&ctx, second_data, hdr.second_size);
    SHA_update(&ctx, &hdr.second_size, sizeof(hdr.second_size));
    sha = SHA_final(&ctx);
    memcpy(hdr.id, sha,
           SHA_DIGEST_SIZE > sizeof(hdr.id) ? sizeof(hdr.id) : SHA_DIGEST_SIZE);

    fd = open(bootimg, O_CREAT | O_TRUNC | O_WRONLY, 0644);
    if(fd < 0) {
        fprintf(stderr,"error: could not create '%s'\n", bootimg);
        return 1;
    }

    if(write(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) goto fail;
    if(write_padding(fd, pagesize, sizeof(hdr))) goto fail;
    if(write_page_padding(fd, pagesize, sizeof(hdr))) goto fail;

    if(write(fd, kernel_data, hdr.kernel_size) != hdr.kernel_size) goto fail;
    if(write_padding(fd, pagesize, hdr.kernel_size)) goto fail;
    if(write_page_padding(fd, pagesize, hdr.kernel_size)) goto fail;

    if(write(fd, ramdisk_data, hdr.ramdisk_size) != hdr.ramdisk_size) goto fail;
    if(write_padding(fd, pagesize, hdr.ramdisk_size)) goto fail;
    if(write_page_padding(fd, pagesize,  hdr.ramdisk_size)) goto fail;

    if(second_data) {
        if(write(fd, second_data, hdr.second_size) != hdr.second_size) goto fail;
        if(write_padding(fd, pagesize, hdr.ramdisk_size)) goto fail;
        if(write_page_padding(fd, pagesize,  hdr.ramdisk_size)) goto fail;
    }

    return 0;

fail:
    unlink(bootimg);
    close(fd);
    fprintf(stderr,"error: failed writing '%s': %s\n", bootimg,
            strerror(errno));
    return 1;
}
示例#23
0
// Load the contents of an MTD partition into the provided
// FileContents.  filename should be a string of the form
// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:...".
// The smallest size_n bytes for which that prefix of the mtd contents
// has the corresponding sha1 hash will be loaded.  It is acceptable
// for a size value to be repeated with different sha1s.  Will return
// 0 on success.
//
// This complexity is needed because if an OTA installation is
// interrupted, the partition might contain either the source or the
// target data, which might be of different lengths.  We need to know
// the length in order to read from MTD (there is no "end-of-file"
// marker), so the caller must specify the possible lengths and the
// hash of the data, and we'll do the load expecting to find one of
// those hashes.
int LoadMTDContents(const char* filename, FileContents* file) {
  char* copy = strdup(filename);
  const char* magic = strtok(copy, ":");
  if (strcmp(magic, "MTD") != 0) {
    fprintf(stderr, "LoadMTDContents called with bad filename (%s)\n",
            filename);
    return -1;
  }
  const char* partition = strtok(NULL, ":");

  int i;
  int colons = 0;
  for (i = 0; filename[i] != '\0'; ++i) {
    if (filename[i] == ':') {
      ++colons;
    }
  }
  if (colons < 3 || colons%2 == 0) {
    fprintf(stderr, "LoadMTDContents called with bad filename (%s)\n",
            filename);
  }

  int pairs = (colons-1)/2;     // # of (size,sha1) pairs in filename
  int* index = malloc(pairs * sizeof(int));
  size_t* size = malloc(pairs * sizeof(size_t));
  char** sha1sum = malloc(pairs * sizeof(char*));

  for (i = 0; i < pairs; ++i) {
    const char* size_str = strtok(NULL, ":");
    size[i] = strtol(size_str, NULL, 10);
    if (size[i] == 0) {
      fprintf(stderr, "LoadMTDContents called with bad size (%s)\n", filename);
      return -1;
    }
    sha1sum[i] = strtok(NULL, ":");
    index[i] = i;
  }

  // sort the index[] array so it indexes the pairs in order of
  // increasing size.
  size_array = size;
  qsort(index, pairs, sizeof(int), compare_size_indices);

  if (!mtd_partitions_scanned) {
    mtd_scan_partitions();
    mtd_partitions_scanned = 1;
  }

  const MtdPartition* mtd = mtd_find_partition_by_name(partition);
  if (mtd == NULL) {
    fprintf(stderr, "mtd partition \"%s\" not found (loading %s)\n",
            partition, filename);
    return -1;
  }

  MtdReadContext* ctx = mtd_read_partition(mtd);
  if (ctx == NULL) {
    fprintf(stderr, "failed to initialize read of mtd partition \"%s\"\n",
            partition);
    return -1;
  }

  SHA_CTX sha_ctx;
  SHA_init(&sha_ctx);
  uint8_t parsed_sha[SHA_DIGEST_SIZE];

  // allocate enough memory to hold the largest size.
  file->data = malloc(size[index[pairs-1]]);
  char* p = (char*)file->data;
  file->size = 0;                // # bytes read so far

  for (i = 0; i < pairs; ++i) {
    // Read enough additional bytes to get us up to the next size
    // (again, we're trying the possibilities in order of increasing
    // size).
    size_t next = size[index[i]] - file->size;
    size_t read = 0;
    if (next > 0) {
      read = mtd_read_data(ctx, p, next);
      if (next != read) {
        fprintf(stderr, "short read (%d bytes of %d) for partition \"%s\"\n",
                read, next, partition);
        free(file->data);
        file->data = NULL;
        return -1;
      }
      SHA_update(&sha_ctx, p, read);
      file->size += read;
    }

    // Duplicate the SHA context and finalize the duplicate so we can
    // check it against this pair's expected hash.
    SHA_CTX temp_ctx;
    memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
    const uint8_t* sha_so_far = SHA_final(&temp_ctx);

    if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
      fprintf(stderr, "failed to parse sha1 %s in %s\n",
              sha1sum[index[i]], filename);
      free(file->data);
      file->data = NULL;
      return -1;
    }

    if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_SIZE) == 0) {
      // we have a match.  stop reading the partition; we'll return
      // the data we've read so far.
      printf("mtd read matched size %d sha %s\n",
             size[index[i]], sha1sum[index[i]]);
      break;
    }

    p += read;
  }

  mtd_read_close(ctx);

  if (i == pairs) {
    // Ran off the end of the list of (size,sha1) pairs without
    // finding a match.
    fprintf(stderr, "contents of MTD partition \"%s\" didn't match %s\n",
            partition, filename);
    free(file->data);
    file->data = NULL;
    return -1;
  }

  const uint8_t* sha_final = SHA_final(&sha_ctx);
  for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
    file->sha1[i] = sha_final[i];
  }

  // Fake some stat() info.
  file->st.st_mode = 0644;
  file->st.st_uid = 0;
  file->st.st_gid = 0;

  free(copy);
  free(index);
  free(size);
  free(sha1sum);

  return 0;
}
int main(int argc, char **argv)
{
    boot_img_hdr hdr;

    char *kernel_fn = 0;
    void *kernel_data = 0;
    char *ramdisk_fn = 0;
    void *ramdisk_data = 0;
    char *second_fn = 0;
    void *second_data = 0;
    char *cmdline = "";
    char *bootimg = 0;
    char *board = "";
    char *dt_fn = 0;
    void *dt_data = 0;
    unsigned pagesize = 2048;
    int fd;
    SHA_CTX ctx;
    uint8_t* sha;
    unsigned base           = 0x10000000;
    unsigned kernel_offset  = 0x00008000;
    unsigned ramdisk_offset = 0x01000000;
    unsigned second_offset  = 0x00f00000;
    unsigned tags_offset    = 0x00000100;

    argc--;
    argv++;

    memset(&hdr, 0, sizeof(hdr));

    while(argc > 0){
        char *arg = argv[0];
        char *val = argv[1];
        if(argc < 2) {
            return usage();
        }
        argc -= 2;
        argv += 2;
        if(!strcmp(arg, "--output") || !strcmp(arg, "-o")) {
            bootimg = val;
        } else if(!strcmp(arg, "--kernel")) {
            kernel_fn = val;
        } else if(!strcmp(arg, "--ramdisk")) {
            ramdisk_fn = val;
        } else if(!strcmp(arg, "--second")) {
            second_fn = val;
        } else if(!strcmp(arg, "--cmdline")) {
            cmdline = val;
        } else if(!strcmp(arg, "--base")) {
            base = strtoul(val, 0, 16);
        } else if(!strcmp(arg, "--kernel_offset")) {
            kernel_offset = strtoul(val, 0, 16);
        } else if(!strcmp(arg, "--ramdisk_offset")) {
            ramdisk_offset = strtoul(val, 0, 16);
        } else if(!strcmp(arg, "--second_offset")) {
            second_offset = strtoul(val, 0, 16);
        } else if(!strcmp(arg, "--tags_offset")) {
            tags_offset = strtoul(val, 0, 16);
        } else if(!strcmp(arg, "--board")) {
            board = val;
        } else if(!strcmp(arg,"--pagesize")) {
            pagesize = strtoul(val, 0, 10);
            if ((pagesize != 2048) && (pagesize != 4096)
                && (pagesize != 8192) && (pagesize != 16384)) {
                fprintf(stderr,"error: unsupported page size %d\n", pagesize);
                return -1;
            }
        } else if(!strcmp(arg, "--dt")) {
            dt_fn = val;
        } else {
            return usage();
        }
    }
    hdr.page_size = pagesize;

    hdr.kernel_addr =  base + kernel_offset;
    hdr.ramdisk_addr = base + ramdisk_offset;
    hdr.second_addr =  base + second_offset;
    hdr.tags_addr =    base + tags_offset;

    if(bootimg == 0) {
        fprintf(stderr,"error: no output filename specified\n");
        return usage();
    }

    if(kernel_fn == 0) {
        fprintf(stderr,"error: no kernel image specified\n");
        return usage();
    }

    if(ramdisk_fn == 0) {
        fprintf(stderr,"error: no ramdisk image specified\n");
        return usage();
    }

    if(strlen(board) >= BOOT_NAME_SIZE) {
        fprintf(stderr,"error: board name too large\n");
        return usage();
    }

    strcpy(hdr.name, board);

    memcpy(hdr.magic, BOOT_MAGIC, BOOT_MAGIC_SIZE);

    if(strlen(cmdline) > (BOOT_ARGS_SIZE - 1)) {
        fprintf(stderr,"error: kernel commandline too large\n");
        return 1;
    }
    strcpy((char*)hdr.cmdline, cmdline);

    kernel_data = load_file(kernel_fn, &hdr.kernel_size);
    if(kernel_data == 0) {
        fprintf(stderr,"error: could not load kernel '%s'\n", kernel_fn);
        return 1;
    }

    if(!strcmp(ramdisk_fn,"NONE")) {
        ramdisk_data = 0;
        hdr.ramdisk_size = 0;
    } else {
        ramdisk_data = load_file(ramdisk_fn, &hdr.ramdisk_size);
        if(ramdisk_data == 0) {
            fprintf(stderr,"error: could not load ramdisk '%s'\n", ramdisk_fn);
            return 1;
        }
    }

    if(second_fn) {
        second_data = load_file(second_fn, &hdr.second_size);
        if(second_data == 0) {
            fprintf(stderr,"error: could not load secondstage '%s'\n", second_fn);
            return 1;
        }
    }

    if(dt_fn) {
        dt_data = load_file(dt_fn, &hdr.dt_size);
        if (dt_data == 0) {
            fprintf(stderr,"error: could not load device tree image '%s'\n", dt_fn);
            return 1;
        }
    }

    /* put a hash of the contents in the header so boot images can be
     * differentiated based on their first 2k.
     */
    SHA_init(&ctx);
    SHA_update(&ctx, kernel_data, hdr.kernel_size);
    SHA_update(&ctx, &hdr.kernel_size, sizeof(hdr.kernel_size));
    SHA_update(&ctx, ramdisk_data, hdr.ramdisk_size);
    SHA_update(&ctx, &hdr.ramdisk_size, sizeof(hdr.ramdisk_size));
    SHA_update(&ctx, second_data, hdr.second_size);
    SHA_update(&ctx, &hdr.second_size, sizeof(hdr.second_size));
    if(dt_data) {
        SHA_update(&ctx, dt_data, hdr.dt_size);
        SHA_update(&ctx, &hdr.dt_size, sizeof(hdr.dt_size));
    }
    sha = SHA_final(&ctx);
    memcpy(hdr.id, sha,
           SHA_DIGEST_SIZE > sizeof(hdr.id) ? sizeof(hdr.id) : SHA_DIGEST_SIZE);

    fd = open(bootimg, O_CREAT | O_TRUNC | O_WRONLY, 0644);
    if(fd < 0) {
        fprintf(stderr,"error: could not create '%s'\n", bootimg);
        return 1;
    }

    if(write(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) goto fail;
    if(write_padding(fd, pagesize, sizeof(hdr))) goto fail;

    if(write(fd, kernel_data, hdr.kernel_size) != hdr.kernel_size) goto fail;
    if(write_padding(fd, pagesize, hdr.kernel_size)) goto fail;

    if(write(fd, ramdisk_data, hdr.ramdisk_size) != hdr.ramdisk_size) goto fail;
    if(write_padding(fd, pagesize, hdr.ramdisk_size)) goto fail;

    if(second_data) {
        if(write(fd, second_data, hdr.second_size) != hdr.second_size) goto fail;
        if(write_padding(fd, pagesize, hdr.ramdisk_size)) goto fail;
    }

    if(dt_data) {
        if(write(fd, dt_data, hdr.dt_size) != hdr.dt_size) goto fail;
        if(write_padding(fd, pagesize, hdr.dt_size)) goto fail;
    }
    return 0;

fail:
    unlink(bootimg);
    close(fd);
    fprintf(stderr,"error: failed writing '%s': %s\n", bootimg,
            strerror(errno));
    return 1;
}
int main(int argc, char **argv)
{
    boot_img_hdr hdr;

    char *kernel_fn = NULL;
    void *kernel_data = NULL;
    char *ramdisk_fn = NULL;
    void *ramdisk_data = NULL;
    char *second_fn = NULL;
    void *second_data = NULL;
    char *cmdline = "";
    char *bootimg = NULL;
    char *board = "";
    char *dt_fn = NULL;
    void *dt_data = NULL;
    uint32_t pagesize = 2048;
    int fd;
    SHA_CTX ctx;
    const uint8_t* sha;
    uint32_t base           = 0x10000000U;
    uint32_t kernel_offset  = 0xFE208100;
    uint32_t ramdisk_offset = 0x00200100;
    uint32_t second_offset  = 0xFF100100;
    uint32_t tags_offset    = 0x00000100U;
    size_t cmdlen;

    argc--;
    argv++;

    memset(&hdr, 0, sizeof(hdr));

    bool get_id = false;
    while(argc > 0){
        char *arg = argv[0];
        if (!strcmp(arg, "--id")) {
            get_id = true;
            argc -= 1;
            argv += 1;
        } else if(argc >= 2) {
            char *val = argv[1];
            argc -= 2;
            argv += 2;
            if(!strcmp(arg, "--output") || !strcmp(arg, "-o")) {
                bootimg = val;
            } else if(!strcmp(arg, "--kernel")) {
                kernel_fn = val;
            } else if(!strcmp(arg, "--ramdisk")) {
                ramdisk_fn = val;
            } else if(!strcmp(arg, "--second")) {
                second_fn = val;
            } else if(!strcmp(arg, "--cmdline")) {
                cmdline = val;
            } else if(!strcmp(arg, "--base")) {
                base = strtoul(val, 0, 16);
            } else if(!strcmp(arg, "--kernel_offset")) {
                kernel_offset = strtoul(val, 0, 16);
            } else if(!strcmp(arg, "--ramdisk_offset")) {
                ramdisk_offset = strtoul(val, 0, 16);
            } else if(!strcmp(arg, "--second_offset")) {
                second_offset = strtoul(val, 0, 16);
            } else if(!strcmp(arg, "--tags_offset")) {
                tags_offset = strtoul(val, 0, 16);
            } else if(!strcmp(arg, "--board")) {
                board = val;
            } else if(!strcmp(arg,"--pagesize")) {
                pagesize = strtoul(val, 0, 10);
                if ((pagesize != 2048) && (pagesize != 4096)
                    && (pagesize != 8192) && (pagesize != 16384)
                    && (pagesize != 32768) && (pagesize != 65536)
                    && (pagesize != 131072)) {
                    fprintf(stderr,"error: unsupported page size %d\n", pagesize);
                    return -1;
                }
            } else if(!strcmp(arg, "--dt")) {
                dt_fn = val;
            } else {
                return usage();
            }
        } else {
            return usage();
        }
    }
    hdr.page_size = pagesize;

    hdr.kernel_addr =  base + kernel_offset;
    hdr.ramdisk_addr = base + ramdisk_offset;
    hdr.second_addr =  base + second_offset;
    hdr.tags_addr =    base + tags_offset;

    if(bootimg == 0) {
        fprintf(stderr,"error: no output filename specified\n");
        return usage();
    }

    if(kernel_fn == 0) {
        fprintf(stderr,"error: no kernel image specified\n");
        return usage();
    }

    if(ramdisk_fn == 0) {
        fprintf(stderr,"error: no ramdisk image specified\n");
        return usage();
    }

    if(strlen(board) >= BOOT_NAME_SIZE) {
        fprintf(stderr,"error: board name too large\n");
        return usage();
    }

    strcpy((char *) hdr.name, board);

    memcpy(hdr.magic, BOOT_MAGIC, BOOT_MAGIC_SIZE);

    cmdlen = strlen(cmdline);
    if(cmdlen > (BOOT_ARGS_SIZE + BOOT_EXTRA_ARGS_SIZE - 2)) {
        fprintf(stderr,"error: kernel commandline too large\n");
        return 1;
    }
    /* Even if we need to use the supplemental field, ensure we
     * are still NULL-terminated */
    strncpy((char *)hdr.cmdline, cmdline, BOOT_ARGS_SIZE - 1);
    hdr.cmdline[BOOT_ARGS_SIZE - 1] = '\0';
    if (cmdlen >= (BOOT_ARGS_SIZE - 1)) {
        cmdline += (BOOT_ARGS_SIZE - 1);
        strncpy((char *)hdr.extra_cmdline, cmdline, BOOT_EXTRA_ARGS_SIZE);
    }

    kernel_data = load_file(kernel_fn, &hdr.kernel_size);
    if(kernel_data == 0) {
        fprintf(stderr,"error: could not load kernel '%s'\n", kernel_fn);
        return 1;
    }

    if(!strcmp(ramdisk_fn,"NONE")) {
        ramdisk_data = 0;
        hdr.ramdisk_size = 0;
    } else {
        ramdisk_data = load_file(ramdisk_fn, &hdr.ramdisk_size);
        if(ramdisk_data == 0) {
            fprintf(stderr,"error: could not load ramdisk '%s'\n", ramdisk_fn);
            return 1;
        }
    }

    if(second_fn) {
        second_data = load_file(second_fn, &hdr.second_size);
        if(second_data == 0) {
            fprintf(stderr,"error: could not load secondstage '%s'\n", second_fn);
            return 1;
        }
    }

    if(dt_fn) {
        dt_data = load_file(dt_fn, &hdr.dt_size);
        if (dt_data == 0) {
            fprintf(stderr,"error: could not load device tree image '%s'\n", dt_fn);
            return 1;
        }
    }

    /* put a hash of the contents in the header so boot images can be
     * differentiated based on their first 2k.
     */
    SHA_init(&ctx);
    SHA_update(&ctx, kernel_data, hdr.kernel_size);
    SHA_update(&ctx, &hdr.kernel_size, sizeof(hdr.kernel_size));
    SHA_update(&ctx, ramdisk_data, hdr.ramdisk_size);
    SHA_update(&ctx, &hdr.ramdisk_size, sizeof(hdr.ramdisk_size));
    SHA_update(&ctx, second_data, hdr.second_size);
    SHA_update(&ctx, &hdr.second_size, sizeof(hdr.second_size));
    if(dt_data) {
        SHA_update(&ctx, dt_data, hdr.dt_size);
        SHA_update(&ctx, &hdr.dt_size, sizeof(hdr.dt_size));
    }
    sha = SHA_final(&ctx);
    memcpy(hdr.id, sha,
           SHA_DIGEST_SIZE > sizeof(hdr.id) ? sizeof(hdr.id) : SHA_DIGEST_SIZE);

    fd = open(bootimg, O_CREAT | O_TRUNC | O_WRONLY, 0644);
    if(fd < 0) {
        fprintf(stderr,"error: could not create '%s'\n", bootimg);
        return 1;
    }

    if(write(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) goto fail;
    if(write_padding(fd, pagesize, sizeof(hdr))) goto fail;

    if(write(fd, kernel_data, hdr.kernel_size) != (ssize_t) hdr.kernel_size) goto fail;
    if(write_padding(fd, pagesize, hdr.kernel_size)) goto fail;

    if(write(fd, ramdisk_data, hdr.ramdisk_size) != (ssize_t) hdr.ramdisk_size) goto fail;
    if(write_padding(fd, pagesize, hdr.ramdisk_size)) goto fail;

    if(second_data) {
        if(write(fd, second_data, hdr.second_size) != (ssize_t) hdr.second_size) goto fail;
        if(write_padding(fd, pagesize, hdr.second_size)) goto fail;
    }

    if(dt_data) {
        if(write(fd, dt_data, hdr.dt_size) != (ssize_t) hdr.dt_size) goto fail;
        if(write_padding(fd, pagesize, hdr.dt_size)) goto fail;
    }

    if (get_id) {
        print_id((uint8_t *) hdr.id, sizeof(hdr.id));
    }

    return 0;

fail:
    unlink(bootimg);
    close(fd);
    fprintf(stderr,"error: failed writing '%s': %s\n", bootimg,
            strerror(errno));
    return 1;
}
示例#26
0
文件: pack.c 项目: zt515/edroid
int pack_main(char *dir, char *bootimg) {
  char tmp[PATH_MAX];
  char *img_info = 0;
  char *kernel_fn;
  void *kernel_data;
  char *ramdisk_fn;
  void *ramdisk_data = 0;
  char *second_fn = 0;
  void *second_data = 0;
  FILE *flag_fn = 0;
  unsigned char *flag_data[512];
  char *board = "";
  char *dt_fn = 0;
  void *dt_data = 0;
 		int fd;
  SHA_CTX ctx;
  const uint8_t *sha;
  int _BOOTIMG_MTK = 0;


  memset(&hdr, 0, sizeof(hdr));
  char *__now_path = getcwd(NULL, NULL);
  hdr.kernel_addr = 0x10008000;
  hdr.ramdisk_addr = 0x11000000;
  hdr.second_addr = 0x10F00000;
  hdr.tags_addr = 0x10000100;
  chdir(dir);
  repack_ramdisk_main(dir);
  sprintf(tmp, "%s/%s", __now_path, bootimg);
  bootimg = tmp;
  kernel_fn = "zImage";
  ramdisk_fn = "ramdisk-new.cpio.gz";
  dt_fn = "dt.img";
  img_info = "img_info.txt";

  if (exist(kernel_fn)) {
    fprintf(stderr, "找不到:%s\n", kernel_fn);
    //exit(-1);
  }
  if (exist(ramdisk_fn)) {
    fprintf(stderr, "找不到:%s\n", ramdisk_fn);
    //exit(-1);
  }
  if (exist(dt_fn)) {
    //fprintf(stderr, "no dt.img\n", dt_fn);
    dt_fn = 0;
  }
  if (exist(img_info)) {
    fprintf(stderr, "找不到:%s\n", img_info);
    //exit(-1);
  }
  if(!exist(".mtk_flag")){
  		_BOOTIMG_MTK = 1;
  }
  read_img_info(img_info);
  if(_BOOTIMG_MTK){
    	cmdline = "";
   }
  hdr.page_size = pagesize;
  strcpy((char *)hdr.name, board);
  memcpy(hdr.magic, BOOT_MAGIC, BOOT_MAGIC_SIZE);
    if(_BOOTIMG_MTK){
 	 // MTK 需要多写入512字节
 	 char *ram_old = ramdisk_fn;
 	 char *ram_new = "ramdisk-new.cpio.gz.revised";
 	 FILE *flag_fn = fopen(".mtk_flag", "rb");
 	 fread(flag_data, 512, 1, flag_fn);
 	 FILE *ram_fn = fopen(ram_old, "rb");
 	 fseek(ram_fn, 0, SEEK_END);
 	 long ram_size = ftell(ram_fn);
 	 fseek(ram_fn, 0, SEEK_SET);
 	 unsigned char buf[ram_size];
 	 fread(buf, ram_size, 1, ram_fn);
 	 FILE *new_fn = fopen(ram_new, "wb");
 	 fwrite(flag_data, 512, 1, new_fn);
 	 fwrite(buf, ram_size, 1, new_fn);
 	 fclose(ram_fn);
 	 fclose(new_fn);
 	 fclose(flag_fn);
 	 unlink(ram_old);
 	 ramdisk_fn = ram_new;
  }
  if (strlen(cmdline) > (BOOT_ARGS_SIZE - 1)) {
    fprintf(stderr, "error: kernel commandline too large\n");
    return 1;
  }
  strcpy((char *)hdr.cmdline, cmdline);

  kernel_data = load_file(kernel_fn, &hdr.kernel_size);
  if (!strcmp(ramdisk_fn, "NONE")) {
    ramdisk_data = 0;
    hdr.ramdisk_size = 0;
  } else {
    ramdisk_data = load_file(ramdisk_fn, &hdr.ramdisk_size);
  }
  if (second_fn) {
    second_data = load_file(second_fn, &hdr.second_size);
    if (second_data == 0) {
      fprintf(stderr, "error: could not load secondstage '%s'\n", second_fn);
      return 1;
    }
  }

  if (dt_fn) {
    dt_data = load_file(dt_fn, &hdr.dt_size);
    if (dt_data == 0) {
      fprintf(stderr, "error: could not load device tree image '%s'\n", dt_fn);
      return 1;
    }
  }

  /* put a hash of the contents in the header so boot images can be
     differentiated based on their first 2k. */
  SHA_init(&ctx);
  SHA_update(&ctx, kernel_data, (int)hdr.kernel_size);
  SHA_update(&ctx, &hdr.kernel_size, (int)sizeof(hdr.kernel_size));
  SHA_update(&ctx, ramdisk_data, hdr.ramdisk_size);
  SHA_update(&ctx, &hdr.ramdisk_size, (int)sizeof(hdr.ramdisk_size));
  SHA_update(&ctx, second_data, (int)hdr.second_size);
  SHA_update(&ctx, &hdr.second_size, (int)sizeof(hdr.second_size));
  if (dt_data) {
    SHA_update(&ctx, dt_data, hdr.dt_size);
    SHA_update(&ctx, &hdr.dt_size, sizeof(hdr.dt_size));
  }
  sha = SHA_final(&ctx);
  memcpy(hdr.id, sha,
         SHA_DIGEST_SIZE > sizeof(hdr.id) ? sizeof(hdr.id) : SHA_DIGEST_SIZE);

  fd = open(bootimg, O_CREAT | O_TRUNC | O_WRONLY, 0777);
  if (fd < 0) {
    fprintf(stderr, "无法创建:'%s'\n", bootimg);
    return 1;
  }

  if (write(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
    goto fail;
  if (write_padding(fd, pagesize, sizeof(hdr)))
    goto fail;

  if (write(fd, kernel_data, hdr.kernel_size) != (signed)hdr.kernel_size)
    goto fail;
  if (write_padding(fd, pagesize, hdr.kernel_size))
    goto fail;
  if (write(fd, ramdisk_data, hdr.ramdisk_size) != (signed)hdr.ramdisk_size)
    goto fail;
  if (write_padding(fd, pagesize, hdr.ramdisk_size))
    goto fail;

  if (second_data) {
    if (write(fd, second_data, hdr.second_size) != (signed)hdr.second_size)
      goto fail;
    if (write_padding(fd, pagesize, hdr.ramdisk_size))
      goto fail;
  }
  if (dt_data) {
    if (write(fd, dt_data, hdr.dt_size) != hdr.dt_size)
      goto fail;
    if (write_padding(fd, pagesize, hdr.dt_size))
      goto fail;
  }

  return 0;

fail:
  unlink(bootimg);
  close(fd);
  fprintf(stderr, "error: failed writing '%s': %s\n", bootimg,
          strerror(errno));
  return 1;
}
示例#27
0
/*
 * Apply the patch given in 'patch_filename' to the source data given
 * by (old_data, old_size).  Write the patched output to the 'output'
 * file, and update the SHA context with the output data as well.
 * Return 0 on success.
 */
int ApplyImagePatch(const unsigned char* old_data, ssize_t old_size,
                    const char* patch_filename,
                    SinkFn sink, void* token, SHA_CTX* ctx) {
  FILE* f;
  if ((f = fopen(patch_filename, "rb")) == NULL) {
    printf("failed to open patch file\n");
    return -1;
  }

  unsigned char header[12];
  if (fread(header, 1, 12, f) != 12) {
    printf("failed to read patch file header\n");
    return -1;
  }

  // IMGDIFF1 uses CHUNK_NORMAL and CHUNK_GZIP.
  // IMGDIFF2 uses CHUNK_NORMAL, CHUNK_DEFLATE, and CHUNK_RAW.
  if (memcmp(header, "IMGDIFF", 7) != 0 ||
      (header[7] != '1' && header[7] != '2')) {
    printf("corrupt patch file header (magic number)\n");
    return -1;
  }

  int num_chunks = Read4(header+8);

  int i;
  for (i = 0; i < num_chunks; ++i) {
    // each chunk's header record starts with 4 bytes.
    unsigned char chunk[4];
    if (fread(chunk, 1, 4, f) != 4) {
      printf("failed to read chunk %d record\n", i);
      return -1;
    }

    int type = Read4(chunk);

    if (type == CHUNK_NORMAL) {
      unsigned char normal_header[24];
      if (fread(normal_header, 1, 24, f) != 24) {
        printf("failed to read chunk %d normal header data\n", i);
        return -1;
      }

      size_t src_start = Read8(normal_header);
      size_t src_len = Read8(normal_header+8);
      size_t patch_offset = Read8(normal_header+16);

      printf("CHUNK %d:  normal   patch offset %d\n", i, patch_offset);

      ApplyBSDiffPatch(old_data + src_start, src_len,
                       patch_filename, patch_offset,
                       sink, token, ctx);
    } else if (type == CHUNK_GZIP) {
      // This branch is basically a duplicate of the CHUNK_DEFLATE
      // branch, with a bit of extra processing for the gzip header
      // and footer.  I've avoided factoring the common code out since
      // this branch will just be deleted when we drop support for
      // IMGDIFF1.

      // gzip chunks have an additional 64 + gzip_header_len + 8 bytes
      // in their chunk header.
      unsigned char* gzip = malloc(64);
      if (fread(gzip, 1, 64, f) != 64) {
        printf("failed to read chunk %d initial gzip header data\n",
                i);
        return -1;
      }
      size_t gzip_header_len = Read4(gzip+60);
      gzip = realloc(gzip, 64 + gzip_header_len + 8);
      if (fread(gzip+64, 1, gzip_header_len+8, f) != gzip_header_len+8) {
        printf("failed to read chunk %d remaining gzip header data\n",
                i);
        return -1;
      }

      size_t src_start = Read8(gzip);
      size_t src_len = Read8(gzip+8);
      size_t patch_offset = Read8(gzip+16);

      size_t expanded_len = Read8(gzip+24);
      size_t target_len = Read8(gzip+32);
      int gz_level = Read4(gzip+40);
      int gz_method = Read4(gzip+44);
      int gz_windowBits = Read4(gzip+48);
      int gz_memLevel = Read4(gzip+52);
      int gz_strategy = Read4(gzip+56);

      printf("CHUNK %d:  gzip     patch offset %d\n", i, patch_offset);

      // Decompress the source data; the chunk header tells us exactly
      // how big we expect it to be when decompressed.

      unsigned char* expanded_source = malloc(expanded_len);
      if (expanded_source == NULL) {
        printf("failed to allocate %d bytes for expanded_source\n",
                expanded_len);
        return -1;
      }

      z_stream strm;
      strm.zalloc = Z_NULL;
      strm.zfree = Z_NULL;
      strm.opaque = Z_NULL;
      strm.avail_in = src_len - (gzip_header_len + 8);
      strm.next_in = (unsigned char*)(old_data + src_start + gzip_header_len);
      strm.avail_out = expanded_len;
      strm.next_out = expanded_source;

      int ret;
      ret = inflateInit2(&strm, -15);
      if (ret != Z_OK) {
        printf("failed to init source inflation: %d\n", ret);
        return -1;
      }

      // Because we've provided enough room to accommodate the output
      // data, we expect one call to inflate() to suffice.
      ret = inflate(&strm, Z_SYNC_FLUSH);
      if (ret != Z_STREAM_END) {
        printf("source inflation returned %d\n", ret);
        return -1;
      }
      // We should have filled the output buffer exactly.
      if (strm.avail_out != 0) {
        printf("source inflation short by %d bytes\n", strm.avail_out);
        return -1;
      }
      inflateEnd(&strm);

      // Next, apply the bsdiff patch (in memory) to the uncompressed
      // data.
      unsigned char* uncompressed_target_data;
      ssize_t uncompressed_target_size;
      if (ApplyBSDiffPatchMem(expanded_source, expanded_len,
                              patch_filename, patch_offset,
                              &uncompressed_target_data,
                              &uncompressed_target_size) != 0) {
        return -1;
      }

      // Now compress the target data and append it to the output.

      // start with the gzip header.
      sink(gzip+64, gzip_header_len, token);
      SHA_update(ctx, gzip+64, gzip_header_len);

      // we're done with the expanded_source data buffer, so we'll
      // reuse that memory to receive the output of deflate.
      unsigned char* temp_data = expanded_source;
      ssize_t temp_size = expanded_len;
      if (temp_size < 32768) {
        // ... unless the buffer is too small, in which case we'll
        // allocate a fresh one.
        free(temp_data);
        temp_data = malloc(32768);
        temp_size = 32768;
      }

      // now the deflate stream
      strm.zalloc = Z_NULL;
      strm.zfree = Z_NULL;
      strm.opaque = Z_NULL;
      strm.avail_in = uncompressed_target_size;
      strm.next_in = uncompressed_target_data;
      ret = deflateInit2(&strm, gz_level, gz_method, gz_windowBits,
                         gz_memLevel, gz_strategy);
      do {
        strm.avail_out = temp_size;
        strm.next_out = temp_data;
        ret = deflate(&strm, Z_FINISH);
        size_t have = temp_size - strm.avail_out;

        if (sink(temp_data, have, token) != have) {
          printf("failed to write %d compressed bytes to output\n",
                  have);
          return -1;
        }
        SHA_update(ctx, temp_data, have);
      } while (ret != Z_STREAM_END);
      deflateEnd(&strm);

      // lastly, the gzip footer.
      sink(gzip+64+gzip_header_len, 8, token);
      SHA_update(ctx, gzip+64+gzip_header_len, 8);

      free(temp_data);
      free(uncompressed_target_data);
      free(gzip);
    } else if (type == CHUNK_RAW) {
      unsigned char raw_header[4];
      if (fread(raw_header, 1, 4, f) != 4) {
        printf("failed to read chunk %d raw header data\n", i);
        return -1;
      }

      size_t data_len = Read4(raw_header);

      printf("CHUNK %d:  raw      data %d\n", i, data_len);

      unsigned char* temp = malloc(data_len);
      if (fread(temp, 1, data_len, f) != data_len) {
          printf("failed to read chunk %d raw data\n", i);
          return -1;
      }
      SHA_update(ctx, temp, data_len);
      if (sink(temp, data_len, token) != data_len) {
          printf("failed to write chunk %d raw data\n", i);
          return -1;
      }
    } else if (type == CHUNK_DEFLATE) {
      // deflate chunks have an additional 60 bytes in their chunk header.
      unsigned char deflate_header[60];
      if (fread(deflate_header, 1, 60, f) != 60) {
        printf("failed to read chunk %d deflate header data\n", i);
        return -1;
      }

      size_t src_start = Read8(deflate_header);
      size_t src_len = Read8(deflate_header+8);
      size_t patch_offset = Read8(deflate_header+16);
      size_t expanded_len = Read8(deflate_header+24);
      size_t target_len = Read8(deflate_header+32);
      int level = Read4(deflate_header+40);
      int method = Read4(deflate_header+44);
      int windowBits = Read4(deflate_header+48);
      int memLevel = Read4(deflate_header+52);
      int strategy = Read4(deflate_header+56);

      printf("CHUNK %d:  deflate  patch offset %d\n", i, patch_offset);

      // Decompress the source data; the chunk header tells us exactly
      // how big we expect it to be when decompressed.

      unsigned char* expanded_source = malloc(expanded_len);
      if (expanded_source == NULL) {
        printf("failed to allocate %d bytes for expanded_source\n",
                expanded_len);
        return -1;
      }

      z_stream strm;
      strm.zalloc = Z_NULL;
      strm.zfree = Z_NULL;
      strm.opaque = Z_NULL;
      strm.avail_in = src_len;
      strm.next_in = (unsigned char*)(old_data + src_start);
      strm.avail_out = expanded_len;
      strm.next_out = expanded_source;

      int ret;
      ret = inflateInit2(&strm, -15);
      if (ret != Z_OK) {
        printf("failed to init source inflation: %d\n", ret);
        return -1;
      }

      // Because we've provided enough room to accommodate the output
      // data, we expect one call to inflate() to suffice.
      ret = inflate(&strm, Z_SYNC_FLUSH);
      if (ret != Z_STREAM_END) {
        printf("source inflation returned %d\n", ret);
        return -1;
      }
      // We should have filled the output buffer exactly.
      if (strm.avail_out != 0) {
        printf("source inflation short by %d bytes\n", strm.avail_out);
        return -1;
      }
      inflateEnd(&strm);

      // Next, apply the bsdiff patch (in memory) to the uncompressed
      // data.
      unsigned char* uncompressed_target_data;
      ssize_t uncompressed_target_size;
      if (ApplyBSDiffPatchMem(expanded_source, expanded_len,
                              patch_filename, patch_offset,
                              &uncompressed_target_data,
                              &uncompressed_target_size) != 0) {
        return -1;
      }

      // Now compress the target data and append it to the output.

      // we're done with the expanded_source data buffer, so we'll
      // reuse that memory to receive the output of deflate.
      unsigned char* temp_data = expanded_source;
      ssize_t temp_size = expanded_len;
      if (temp_size < 32768) {
        // ... unless the buffer is too small, in which case we'll
        // allocate a fresh one.
        free(temp_data);
        temp_data = malloc(32768);
        temp_size = 32768;
      }

      // now the deflate stream
      strm.zalloc = Z_NULL;
      strm.zfree = Z_NULL;
      strm.opaque = Z_NULL;
      strm.avail_in = uncompressed_target_size;
      strm.next_in = uncompressed_target_data;
      ret = deflateInit2(&strm, level, method, windowBits, memLevel, strategy);
      do {
        strm.avail_out = temp_size;
        strm.next_out = temp_data;
        ret = deflate(&strm, Z_FINISH);
        size_t have = temp_size - strm.avail_out;

        if (sink(temp_data, have, token) != have) {
          printf("failed to write %d compressed bytes to output\n",
                  have);
          return -1;
        }
        SHA_update(ctx, temp_data, have);
      } while (ret != Z_STREAM_END);
      deflateEnd(&strm);

      free(temp_data);
      free(uncompressed_target_data);
    } else {
      printf("patch chunk %d is unknown type %d\n", i, type);
      return -1;
    }
  }

  return 0;
}
// Look for an RSA signature embedded in the .ZIP file comment given
// the path to the zip.  Verify it matches one of the given public
// keys.
//
// Return VERIFY_SUCCESS, VERIFY_FAILURE (if any error is encountered
// or no key matches the signature).
int verify_file(unsigned char* addr, size_t length) {
    //ui->SetProgress(0.0);

    int numKeys;
    Certificate* pKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys);
    if (pKeys == NULL) {
        LOGE("Failed to load keys\n");
        return INSTALL_CORRUPT;
    }
    LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE);

    // An archive with a whole-file signature will end in six bytes:
    //
    //   (2-byte signature start) $ff $ff (2-byte comment size)
    //
    // (As far as the ZIP format is concerned, these are part of the
    // archive comment.)  We start by reading this footer, this tells
    // us how far back from the end we have to start reading to find
    // the whole comment.

#define FOOTER_SIZE 6

    if (length < FOOTER_SIZE) {
        LOGE("not big enough to contain footer\n");
        return VERIFY_FAILURE;
    }

    unsigned char* footer = addr + length - FOOTER_SIZE;

    if (footer[2] != 0xff || footer[3] != 0xff) {
        LOGE("footer is wrong\n");
        return VERIFY_FAILURE;
    }

    size_t comment_size = footer[4] + (footer[5] << 8);
    size_t signature_start = footer[0] + (footer[1] << 8);
    LOGI("comment is %zu bytes; signature %zu bytes from end\n",
         comment_size, signature_start);

    if (signature_start <= FOOTER_SIZE) {
        LOGE("Signature start is in the footer");
        return VERIFY_FAILURE;
    }

#define EOCD_HEADER_SIZE 22

    // The end-of-central-directory record is 22 bytes plus any
    // comment length.
    size_t eocd_size = comment_size + EOCD_HEADER_SIZE;

    if (length < eocd_size) {
        LOGE("not big enough to contain EOCD\n");
        return VERIFY_FAILURE;
    }

    // Determine how much of the file is covered by the signature.
    // This is everything except the signature data and length, which
    // includes all of the EOCD except for the comment length field (2
    // bytes) and the comment data.
    size_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2;

    unsigned char* eocd = addr + length - eocd_size;

    // If this is really is the EOCD record, it will begin with the
    // magic number $50 $4b $05 $06.
    if (eocd[0] != 0x50 || eocd[1] != 0x4b ||
        eocd[2] != 0x05 || eocd[3] != 0x06) {
        LOGE("signature length doesn't match EOCD marker\n");
        return VERIFY_FAILURE;
    }

    size_t i;
    for (i = 4; i < eocd_size-3; ++i) {
        if (eocd[i  ] == 0x50 && eocd[i+1] == 0x4b &&
            eocd[i+2] == 0x05 && eocd[i+3] == 0x06) {
            // if the sequence $50 $4b $05 $06 appears anywhere after
            // the real one, minzip will find the later (wrong) one,
            // which could be exploitable.  Fail verification if
            // this sequence occurs anywhere after the real one.
            LOGE("EOCD marker occurs after start of EOCD\n");
            return VERIFY_FAILURE;
        }
    }

#define BUFFER_SIZE 4096

    bool need_sha1 = false;
    bool need_sha256 = false;
    for (i = 0; i < numKeys; ++i) {
        switch (pKeys[i].hash_len) {
            case SHA_DIGEST_SIZE: need_sha1 = true; break;
            case SHA256_DIGEST_SIZE: need_sha256 = true; break;
        }
    }

    SHA_CTX sha1_ctx;
    SHA256_CTX sha256_ctx;
    SHA_init(&sha1_ctx);
    SHA256_init(&sha256_ctx);

    double frac = -1.0;
    size_t so_far = 0;
    while (so_far < signed_len) {
        size_t size = signed_len - so_far;
        if (size > BUFFER_SIZE) size = BUFFER_SIZE;

        if (need_sha1) SHA_update(&sha1_ctx, addr + so_far, size);
        if (need_sha256) SHA256_update(&sha256_ctx, addr + so_far, size);
        so_far += size;

        double f = so_far / (double)signed_len;
        if (f > frac + 0.02 || size == so_far) {
            //ui->SetProgress(f);
            frac = f;
        }
    }

    const uint8_t* sha1 = SHA_final(&sha1_ctx);
    const uint8_t* sha256 = SHA256_final(&sha256_ctx);

    uint8_t* sig_der = NULL;
    size_t sig_der_length = 0;

    size_t signature_size = signature_start - FOOTER_SIZE;
    if (!read_pkcs7(eocd + eocd_size - signature_start, signature_size, &sig_der,
            &sig_der_length)) {
        LOGE("Could not find signature DER block\n");
        return VERIFY_FAILURE;
    }

    /*
     * Check to make sure at least one of the keys matches the signature. Since
     * any key can match, we need to try each before determining a verification
     * failure has happened.
     */
    for (i = 0; i < numKeys; ++i) {
        const uint8_t* hash;
        switch (pKeys[i].hash_len) {
            case SHA_DIGEST_SIZE: hash = sha1; break;
            case SHA256_DIGEST_SIZE: hash = sha256; break;
            default: continue;
        }

        // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that
        // the signing tool appends after the signature itself.
        if (pKeys[i].key_type == Certificate::RSA) {
            if (sig_der_length < RSANUMBYTES) {
                // "signature" block isn't big enough to contain an RSA block.
                LOGI("signature is too short for RSA key %zu\n", i);
                continue;
            }

            if (!RSA_verify(pKeys[i].rsa, sig_der, RSANUMBYTES,
                            hash, pKeys[i].hash_len)) {
                LOGI("failed to verify against RSA key %zu\n", i);
                continue;
            }

            LOGI("whole-file signature verified against RSA key %zu\n", i);
            free(sig_der);
            return VERIFY_SUCCESS;
        } else if (pKeys[i].key_type == Certificate::EC
                && pKeys[i].hash_len == SHA256_DIGEST_SIZE) {
            p256_int r, s;
            if (!dsa_sig_unpack(sig_der, sig_der_length, &r, &s)) {
                LOGI("Not a DSA signature block for EC key %zu\n", i);
                continue;
            }

            p256_int p256_hash;
            p256_from_bin(hash, &p256_hash);
            if (!p256_ecdsa_verify(&(pKeys[i].ec->x), &(pKeys[i].ec->y),
                                   &p256_hash, &r, &s)) {
                LOGI("failed to verify against EC key %zu\n", i);
                continue;
            }

            LOGI("whole-file signature verified against EC key %zu\n", i);
            free(sig_der);
            return VERIFY_SUCCESS;
        } else {
            LOGI("Unknown key type %d\n", pKeys[i].key_type);
        }
		LOGI("i: %i, eocd_size: %i, RSANUMBYTES: %i\n", i, eocd_size, RSANUMBYTES);
    }
    free(sig_der);
    LOGE("failed to verify whole-file signature\n");
    return VERIFY_FAILURE;
}
示例#29
0
static int LoadPartitionContents(const char* filename, FileContents* file) {
    char* copy = strdup(filename);
    const char* magic = strtok(copy, ":");

    enum PartitionType type;

    if (strcmp(magic, "EMMC") == 0) {
        type = EMMC;
    } else {
        printf("LoadPartitionContents called with bad filename (%s)\n",
               filename);
        return -1;
    }
    const char* partition = strtok(NULL, ":");

    int i;
    int colons = 0;
    for (i = 0; filename[i] != '\0'; ++i) {
        if (filename[i] == ':') {
            ++colons;
        }
    }
    if (colons < 3 || colons%2 == 0) {
        printf("LoadPartitionContents called with bad filename (%s)\n",
               filename);
    }

    int pairs = (colons-1)/2;     // # of (size,sha1) pairs in filename
    int* index = malloc(pairs * sizeof(int));
    size_t* size = malloc(pairs * sizeof(size_t));
    char** sha1sum = malloc(pairs * sizeof(char*));

    for (i = 0; i < pairs; ++i) {
        const char* size_str = strtok(NULL, ":");
        size[i] = strtol(size_str, NULL, 10);
        if (size[i] == 0) {
            printf("LoadPartitionContents called with bad size (%s)\n", filename);
            return -1;
        }
        sha1sum[i] = strtok(NULL, ":");
        index[i] = i;
    }

    // sort the index[] array so it indexes the pairs in order of
    // increasing size.
    size_array = size;
    qsort(index, pairs, sizeof(int), compare_size_indices);

    FILE* dev = NULL;

    switch (type) {
        case EMMC:
            dev = fopen(partition, "rb");
            if (dev == NULL) {
                printf("failed to open emmc partition \"%s\": %s\n",
                       partition, strerror(errno));
                return -1;
            }
    }

    SHA_CTX sha_ctx;
    SHA_init(&sha_ctx);
    uint8_t parsed_sha[SHA_DIGEST_SIZE];

    // allocate enough memory to hold the largest size.
    file->data = malloc(size[index[pairs-1]]);
    char* p = (char*)file->data;
    file->size = 0;                // # bytes read so far

    for (i = 0; i < pairs; ++i) {
        // Read enough additional bytes to get us up to the next size
        // (again, we're trying the possibilities in order of increasing
        // size).
        size_t next = size[index[i]] - file->size;
        size_t read = 0;
        if (next > 0) {
            switch (type) {
                case EMMC:
                    read = fread(p, 1, next, dev);
                    break;
            }
            if (next != read) {
                printf("short read (%d bytes of %d) for partition \"%s\"\n",
                       read, next, partition);
                free(file->data);
                file->data = NULL;
                return -1;
            }
            SHA_update(&sha_ctx, p, read);
            file->size += read;
        }

        // Duplicate the SHA context and finalize the duplicate so we can
        // check it against this pair's expected hash.
        SHA_CTX temp_ctx;
        memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
        const uint8_t* sha_so_far = SHA_final(&temp_ctx);

        if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
            printf("failed to parse sha1 %s in %s\n",
                   sha1sum[index[i]], filename);
            free(file->data);
            file->data = NULL;
            return -1;
        }

        if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_SIZE) == 0) {
            // we have a match.  stop reading the partition; we'll return
            // the data we've read so far.
            printf("partition read matched size %d sha %s\n",
                   size[index[i]], sha1sum[index[i]]);
            break;
        }

        p += read;
    }

    switch (type) {
        case EMMC:
            fclose(dev);
            break;
    }


    if (i == pairs) {
        // Ran off the end of the list of (size,sha1) pairs without
        // finding a match.
        printf("contents of partition \"%s\" didn't match %s\n",
               partition, filename);
        free(file->data);
        file->data = NULL;
        return -1;
    }

    const uint8_t* sha_final = SHA_final(&sha_ctx);
    for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
        file->sha1[i] = sha_final[i];
    }

    // Fake some stat() info.
    file->st.st_mode = 0644;
    file->st.st_uid = 0;
    file->st.st_gid = 0;

    free(copy);
    free(index);
    free(size);
    free(sha1sum);

    return 0;
}
示例#30
0
/*
 * Apply the patch given in 'patch_filename' to the source data given
 * by (old_data, old_size).  Write the patched output to the 'output'
 * file, and update the SHA context with the output data as well.
 * Return 0 on success.
 */
int ApplyImagePatch(const unsigned char* old_data, ssize_t old_size,
                    const Value* patch,
                    SinkFn sink, void* token, SHA_CTX* ctx,
                    const Value* bonus_data) {
    ssize_t pos = 12;
    char* header = patch->data;
    if (patch->size < 12) {
        printf("patch too short to contain header\n");
        return -1;
    }

    // IMGDIFF2 uses CHUNK_NORMAL, CHUNK_DEFLATE, and CHUNK_RAW.
    // (IMGDIFF1, which is no longer supported, used CHUNK_NORMAL and
    // CHUNK_GZIP.)
    if (memcmp(header, "IMGDIFF2", 8) != 0) {
        printf("corrupt patch file header (magic number)\n");
        return -1;
    }

    int num_chunks = Read4(header+8);

    int i;
    for (i = 0; i < num_chunks; ++i) {
        // each chunk's header record starts with 4 bytes.
        if (pos + 4 > patch->size) {
            printf("failed to read chunk %d record\n", i);
            return -1;
        }
        int type = Read4(patch->data + pos);
        pos += 4;

        if (type == CHUNK_NORMAL) {
            char* normal_header = patch->data + pos;
            pos += 24;
            if (pos > patch->size) {
                printf("failed to read chunk %d normal header data\n", i);
                return -1;
            }

            size_t src_start = Read8(normal_header);
            size_t src_len = Read8(normal_header+8);
            size_t patch_offset = Read8(normal_header+16);

            ApplyBSDiffPatch(old_data + src_start, src_len,
                             patch, patch_offset, sink, token, ctx);
        } else if (type == CHUNK_RAW) {
            char* raw_header = patch->data + pos;
            pos += 4;
            if (pos > patch->size) {
                printf("failed to read chunk %d raw header data\n", i);
                return -1;
            }

            ssize_t data_len = Read4(raw_header);

            if (pos + data_len > patch->size) {
                printf("failed to read chunk %d raw data\n", i);
                return -1;
            }
            SHA_update(ctx, patch->data + pos, data_len);
            if (sink((unsigned char*)patch->data + pos,
                     data_len, token) != data_len) {
                printf("failed to write chunk %d raw data\n", i);
                return -1;
            }
            pos += data_len;
        } else if (type == CHUNK_DEFLATE) {
            // deflate chunks have an additional 60 bytes in their chunk header.
            char* deflate_header = patch->data + pos;
            pos += 60;
            if (pos > patch->size) {
                printf("failed to read chunk %d deflate header data\n", i);
                return -1;
            }

            size_t src_start = Read8(deflate_header);
            size_t src_len = Read8(deflate_header+8);
            size_t patch_offset = Read8(deflate_header+16);
            size_t expanded_len = Read8(deflate_header+24);
            size_t target_len = Read8(deflate_header+32);
            int level = Read4(deflate_header+40);
            int method = Read4(deflate_header+44);
            int windowBits = Read4(deflate_header+48);
            int memLevel = Read4(deflate_header+52);
            int strategy = Read4(deflate_header+56);

            // Decompress the source data; the chunk header tells us exactly
            // how big we expect it to be when decompressed.

            // Note: expanded_len will include the bonus data size if
            // the patch was constructed with bonus data.  The
            // deflation will come up 'bonus_size' bytes short; these
            // must be appended from the bonus_data value.
            size_t bonus_size = (i == 1 && bonus_data != NULL) ? bonus_data->size : 0;

            unsigned char* expanded_source = malloc(expanded_len);
            if (expanded_source == NULL) {
                printf("failed to allocate %d bytes for expanded_source\n",
                       expanded_len);
                return -1;
            }

            z_stream strm;
            strm.zalloc = Z_NULL;
            strm.zfree = Z_NULL;
            strm.opaque = Z_NULL;
            strm.avail_in = src_len;
            strm.next_in = (unsigned char*)(old_data + src_start);
            strm.avail_out = expanded_len;
            strm.next_out = expanded_source;

            int ret;
            ret = inflateInit2(&strm, -15);
            if (ret != Z_OK) {
                printf("failed to init source inflation: %d\n", ret);
                return -1;
            }

            // Because we've provided enough room to accommodate the output
            // data, we expect one call to inflate() to suffice.
            ret = inflate(&strm, Z_SYNC_FLUSH);
            if (ret != Z_STREAM_END) {
                printf("source inflation returned %d\n", ret);
                return -1;
            }
            // We should have filled the output buffer exactly, except
            // for the bonus_size.
            if (strm.avail_out != bonus_size) {
                printf("source inflation short by %zu bytes\n", strm.avail_out-bonus_size);
                return -1;
            }
            inflateEnd(&strm);

            if (bonus_size) {
                memcpy(expanded_source + (expanded_len - bonus_size),
                       bonus_data->data, bonus_size);
            }

            // Next, apply the bsdiff patch (in memory) to the uncompressed
            // data.
            unsigned char* uncompressed_target_data;
            ssize_t uncompressed_target_size;
            if (ApplyBSDiffPatchMem(expanded_source, expanded_len,
                                    patch, patch_offset,
                                    &uncompressed_target_data,
                                    &uncompressed_target_size) != 0) {
                return -1;
            }

            // Now compress the target data and append it to the output.

            // we're done with the expanded_source data buffer, so we'll
            // reuse that memory to receive the output of deflate.
            unsigned char* temp_data = expanded_source;
            ssize_t temp_size = expanded_len;
            if (temp_size < 32768) {
                // ... unless the buffer is too small, in which case we'll
                // allocate a fresh one.
                free(temp_data);
                temp_data = malloc(32768);
                temp_size = 32768;
            }

            // now the deflate stream
            strm.zalloc = Z_NULL;
            strm.zfree = Z_NULL;
            strm.opaque = Z_NULL;
            strm.avail_in = uncompressed_target_size;
            strm.next_in = uncompressed_target_data;
            ret = deflateInit2(&strm, level, method, windowBits, memLevel, strategy);
            do {
                strm.avail_out = temp_size;
                strm.next_out = temp_data;
                ret = deflate(&strm, Z_FINISH);
                ssize_t have = temp_size - strm.avail_out;

                if (sink(temp_data, have, token) != have) {
                    printf("failed to write %ld compressed bytes to output\n",
                           (long)have);
                    return -1;
                }
                SHA_update(ctx, temp_data, have);
            } while (ret != Z_STREAM_END);
            deflateEnd(&strm);

            free(temp_data);
            free(uncompressed_target_data);
        } else {
            printf("patch chunk %d is unknown type %d\n", i, type);
            return -1;
        }
    }

    return 0;
}