Exemplo n.º 1
0
/**
 * Do next chunk of hashing work, if any.
 */
static void vboot_hash_next_chunk(void)
{
	int size;

	/* Handle abort */
	if (want_abort) {
		in_progress = 0;
		vboot_hash_abort();
		return;
	}

	/* Compute the next chunk of hash */
	size = MIN(CHUNK_SIZE, data_size - curr_pos);
	SHA256_update(&ctx, (const uint8_t *)(CONFIG_FLASH_BASE +
					      data_offset + curr_pos), size);

	curr_pos += size;
	if (curr_pos >= data_size) {
		/* Store the final hash */
		hash = SHA256_final(&ctx);
		CPRINTS("hash done %.*h", SHA256_DIGEST_SIZE, hash);

		in_progress = 0;

		/* Handle receiving abort during finalize */
		if (want_abort)
			vboot_hash_abort();

		return;
	}

	/* If we're still here, more work to do; come back later */
	hook_call_deferred(vboot_hash_next_chunk, WORK_INTERVAL_US);
}
Exemplo n.º 2
0
void generate_id_sha256(boot_img_hdr_v2 *hdr, void *kernel_data, void *ramdisk_data,
                        void *second_data, void *dt_data, void *recovery_dtbo_data, void *dtb_data)
{
    SHA256_CTX ctx;
    const uint8_t *sha;

    SHA256_init(&ctx);
    SHA256_update(&ctx, kernel_data, hdr->kernel_size);
    SHA256_update(&ctx, &hdr->kernel_size, sizeof(hdr->kernel_size));
    SHA256_update(&ctx, ramdisk_data, hdr->ramdisk_size);
    SHA256_update(&ctx, &hdr->ramdisk_size, sizeof(hdr->ramdisk_size));
    SHA256_update(&ctx, second_data, hdr->second_size);
    SHA256_update(&ctx, &hdr->second_size, sizeof(hdr->second_size));
    if(dt_data) {
        SHA256_update(&ctx, dt_data, hdr->dt_size);
        SHA256_update(&ctx, &hdr->dt_size, sizeof(hdr->dt_size));
    } else if(hdr->header_version > 0) {
        SHA256_update(&ctx, recovery_dtbo_data, hdr->recovery_dtbo_size);
        SHA256_update(&ctx, &hdr->recovery_dtbo_size, sizeof(hdr->recovery_dtbo_size));
        if(hdr->header_version > 1) {
            SHA256_update(&ctx, dtb_data, hdr->dtb_size);
            SHA256_update(&ctx, &hdr->dtb_size, sizeof(hdr->dtb_size));
        }
    }
    sha = SHA256_final(&ctx);
    memcpy(hdr->id, sha, SHA256_DIGEST_SIZE > sizeof(hdr->id) ? sizeof(hdr->id) : SHA256_DIGEST_SIZE);
}
Exemplo n.º 3
0
void check_rw_signature(void)
{
	struct sha256_ctx ctx;
	int good, res;
	uint8_t *hash;
	uint32_t *rsa_workbuf;

	/* Only the Read-Only firmware needs to do the signature check */
	if (system_get_image_copy() != SYSTEM_IMAGE_RO)
		return;

	/* Check if we have a RW firmware flashed */
	if (*rw_rst == 0xffffffff)
		return;

	CPRINTS("Verifying RW image...");

	/* Large buffer for RSA computation : could be re-use afterwards... */
	res = shared_mem_acquire(3 * RSANUMBYTES, (char **)&rsa_workbuf);
	if (res) {
		CPRINTS("No memory for RW verification");
		return;
	}

	/* SHA-256 Hash of the RW firmware */
	/* TODO(crosbug.com/p/44803): Do we have to hash the whole region? */
	SHA256_init(&ctx);
	SHA256_update(&ctx, (void *)CONFIG_PROGRAM_MEMORY_BASE
		      + CONFIG_RW_MEM_OFF,
		      CONFIG_RW_SIZE - CONFIG_RW_SIG_SIZE);
	hash = SHA256_final(&ctx);

	good = rsa_verify((const struct rsa_public_key *)CONFIG_RO_PUBKEY_ADDR,
			  (const uint8_t *)CONFIG_RW_SIG_ADDR,
			  hash, rsa_workbuf);
	if (good) {
		CPRINTS("RW image verified");
		/* Jump to the RW firmware */
		system_run_image_copy(SYSTEM_IMAGE_RW);
	} else {
		CPRINTS("RSA verify FAILED");
		pd_log_event(PD_EVENT_ACC_RW_FAIL, 0, 0, NULL);
		/* RW firmware is invalid : do not jump there */
		if (system_is_locked())
			system_disable_jump();
	}
	shared_mem_release(rsa_workbuf);
}
Exemplo n.º 4
0
bool manifest_compute_sha256(struct SHA256_ctx *ctx, FILE *f, unsigned long len)
{
  unsigned long pos = 0;

  SHA256_init(ctx);

  while(pos < len)
  {
    unsigned long block_size = MIN(BLOCK_SIZE, len - pos);
    char block[BLOCK_SIZE];

    if(fread(block, block_size, 1, f) != 1)
      return false;

    SHA256_update(ctx, block, block_size);
    pos += block_size;
  }

  SHA256_final(ctx);
  return true;
}
Exemplo n.º 5
0
char *
util_hash_sha256_image_file_new(const char *image_file)
{
	FILE *fp = NULL;
	SHA256_CTX ctx;
	SHA256_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) {
		SHA256_update(&ctx, buf, len);
	}
	fclose(fp);

	return convert_bin_to_hex_new(SHA256_final(&ctx), SHA256_DIGEST_SIZE);
}
// 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;
}
Exemplo n.º 7
0
int verify_file(const char* path, const Certificate* 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) {
        LOGE("footer is wrong\n");
        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

    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);
    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;
        }
        if (need_sha1) SHA_update(&sha1_ctx, buffer, size);
        if (need_sha256) SHA256_update(&sha256_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(&sha1_ctx);
    const uint8_t* sha256 = SHA256_final(&sha256_ctx);

    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 (RSA_verify(pKeys[i].public_key, eocd + eocd_size - 6 - RSANUMBYTES,
                       RSANUMBYTES, hash, pKeys[i].hash_len)) {
            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;
}
ReturnValue BleApiTest_Sign(pBleDevice dev, uint32_t *ctr, int expectedSW12, bool checkOnly,
			 bool corruptKH, bool corruptAddId)
{
	ReturnValue retval;

	U2F_AUTHENTICATE_REQ authReq;
	unsigned char reply[2048];
	unsigned int replyLength = sizeof(reply);
	unsigned char request[256];
	unsigned int requestlen;
	unsigned char replyCmd;

	// pick random challenge and use registered appId.
	for (size_t i = 0; i < sizeof(authReq.nonce); ++i)
		authReq.nonce[i] = rand();
	memcpy(authReq.appId, regReq.appId, sizeof(authReq.appId));
	authReq.keyHandleLen = regRsp.keyHandleLen;
	memcpy(authReq.keyHandle, regRsp.keyHandleCertSig,
	       authReq.keyHandleLen);

	if (corruptKH)
		authReq.keyHandle[0] ^= 0x55;
	if (corruptAddId)
		authReq.appId[0] ^= 0xAA;

	uint64_t t = dev->TimeMs();

	/* prepare register request */
	request[0] = 0x00;
	request[1] = U2F_INS_AUTHENTICATE;
	request[2] = checkOnly ? U2F_AUTH_CHECK_ONLY : U2F_AUTH_ENFORCE;
	request[3] = 0x00;
	request[4] = 0x00;
	request[5] = 0x00;
	request[6] = U2F_NONCE_SIZE + U2F_APPID_SIZE + 1 + authReq.keyHandleLen;
	memcpy(request + 7, reinterpret_cast < char *>(&authReq), request[6]);
	requestlen = 7 + request[6];
	request[requestlen++] = 0x00;
	request[requestlen++] = 0x00;

	/* write command */
	retval =
	    dev->CommandWrite(FIDO_BLE_CMD_MSG, request, requestlen, &replyCmd,
			      reply, &replyLength);
	CHECK_EQ(retval, ReturnValue::BLEAPI_ERROR_SUCCESS);

	if (expectedSW12 != FIDO_RESP_SUCCESS) {
		CHECK_EQ(expectedSW12, bytes2short(reply, replyLength - 2), "Returned error does not match expected value.");
		CHECK_EQ(replyLength, 2, "Returned value does not match expected length.");
		return ReturnValue::BLEAPI_ERROR_SUCCESS;
	}

	CHECK_EQ(replyCmd, FIDO_BLE_CMD_MSG, "Reply is not a FIDO_BLE_CMD_MSG (0x83)");
	CHECK_EQ(FIDO_RESP_SUCCESS, bytes2short(reply, replyLength - 2), "Status code is not FIDO_RESP_SUCCESS (0x9000)");
	CHECK_NE(replyLength, 2, "Reply length is only status code.");
	CHECK_LE(replyLength - 2, sizeof(U2F_AUTHENTICATE_RESP), "Returned authentication response does not match expected length.");

	U2F_AUTHENTICATE_RESP resp;
	memcpy(&resp, reply, replyLength - 2);

	CHECK_EQ(resp.flags, 0x01, "Flags value in authentication response is always 1");

	INFO << "Sign: " << (replyLength - 2) << " bytes in "
	    << ((float)(dev->TimeMs() - t)) / 1000.0 << "s";

	// Parse signature from authenticate response.
	p256_int sig_r, sig_s;
	CHECK_EQ(1, dsa_sig_unpack(resp.sig,
				   replyLength - 2 - sizeof(resp.flags) -
				   sizeof(resp.ctr), &sig_r, &sig_s));

	// Compute hash as integer.
	p256_int h;
	SHA256_CTX sha;
	SHA256_init(&sha);
	SHA256_update(&sha, regReq.appId, sizeof(regReq.appId));	// O
	SHA256_update(&sha, &resp.flags, sizeof(resp.flags));	// T
	SHA256_update(&sha, &resp.ctr, sizeof(resp.ctr));	// CTR
	SHA256_update(&sha, authReq.nonce, sizeof(authReq.nonce));	// d
	p256_from_bin(SHA256_final(&sha), &h);

	// Parse public key from registration response.
	p256_int pk_x, pk_y;
	p256_from_bin(regRsp.pubKey.x, &pk_x);
	p256_from_bin(regRsp.pubKey.y, &pk_y);

	// Verify signature.
	CHECK_EQ(1, p256_ecdsa_verify(&pk_x, &pk_y, &h, &sig_r, &sig_s), "Signature does not match.");

  *ctr = ntohl(resp.ctr);

	return ReturnValue::BLEAPI_ERROR_SUCCESS;
}
ReturnValue BleApiTest_Enroll(pBleDevice dev, int expectedSW12)
{
	uint64_t t = dev->TimeMs();

	ReturnValue retval;
	int i;
	unsigned char reply[2048];
	unsigned int replyLength = sizeof(reply);
	unsigned char request[256];
	unsigned int requestlen;
	unsigned char replyCmd;

	memset(reply, 0, sizeof(reply));

	/* generate appid and nonce */
	for (i = 0; i < sizeof(regReq.appId); i++)
		regReq.appId[i] = (rand() & 0xFF);
	for (i = 0; i < sizeof(regReq.nonce); i++)
		regReq.nonce[i] = (rand() & 0xFF);

	/* prepare register request */
	request[0] = 0x00;
	request[1] = 0x01;
	request[2] = 0x00;
	request[3] = 0x00;
	request[4] = 0x00;
	request[5] = 0x00;
	request[6] = sizeof(regReq.nonce) + sizeof(regReq.appId);
	memcpy(request + 7, regReq.nonce, sizeof(regReq.nonce));
	memcpy(request + 7 + sizeof(regReq.nonce), regReq.appId,
	       sizeof(regReq.appId));
	requestlen = 7 + sizeof(regReq.nonce) + sizeof(regReq.appId);
	request[requestlen++] = 0x00;
	request[requestlen++] = 0x00;

	/* write command */
	retval =
	    dev->CommandWrite(FIDO_BLE_CMD_MSG, request, requestlen, &replyCmd,
			      reply, &replyLength);
	CHECK_EQ(retval, ReturnValue::BLEAPI_ERROR_SUCCESS);

	if (expectedSW12 != FIDO_RESP_SUCCESS) {
		CHECK_EQ(expectedSW12, bytes2short(reply, replyLength - 2), "Returned error does not match expected value.");
		CHECK_EQ(replyLength, 2, "Returned value does not match expected length.");
		return ReturnValue::BLEAPI_ERROR_SUCCESS;
	}

	/* check reply */
	CHECK_EQ(replyCmd, FIDO_BLE_CMD_MSG, "Reply is not a FIDO_BLE_CMD_MSG (0x83)");
	CHECK_EQ(FIDO_RESP_SUCCESS, bytes2short(reply, replyLength - 2), "Status code is not FIDO_RESP_SUCCESS (0x9000)");
	CHECK_NE(replyLength, 2, "Reply length is only status code.");

	CHECK_LE(replyLength - 2, sizeof(U2F_REGISTER_RESP), "Returned register response does not match expected length.");

	memcpy(&regRsp, reply, replyLength - 2);

	CHECK_EQ(regRsp.registerId, U2F_REGISTER_ID, "Register ID is not 0x05");
	CHECK_EQ(regRsp.pubKey.format, UNCOMPRESSED_POINT, "Public Key format is not uncompressed point.");

	INFO << "Enroll: " << (replyLength -
			       2) << " bytes in " << ((float)(dev->TimeMs() -
							      t)) /
	    1000.0 << "s";

	// Check crypto of enroll response.
	std::string cert;
	CHECK_EQ(getCertificate(regRsp, &cert), true, "Cannot extract certificate.");
	INFO << "cert: " << bytes2ascii(cert);

	std::string pk;
	CHECK_EQ(getSubjectPublicKey(cert, &pk), true, "Cannot extract public key.");
	INFO << "pk  : " << bytes2ascii(pk);

	std::string sig;
	CHECK_EQ(getSignature(regRsp, static_cast<int>(cert.size()), &sig), true, "Cannot extract signature.");
	INFO << "sig : " << bytes2ascii(sig);

	// Parse signature into two integers.
	p256_int sig_r, sig_s;
	CHECK_EQ(1, dsa_sig_unpack((uint8_t *) (sig.data()), static_cast<int>(sig.size()),
				   &sig_r, &sig_s), "Cannot unpack signature");

	// Compute hash as integer.
	const uint8_t *hash;
	p256_int h;
	SHA256_CTX sha;
	SHA256_init(&sha);
	uint8_t rfu = 0;
	SHA256_update(&sha, &rfu, sizeof(rfu));	// 0x00
	SHA256_update(&sha, regReq.appId, sizeof(regReq.appId));	// O
	SHA256_update(&sha, regReq.nonce, sizeof(regReq.nonce));	// d
	SHA256_update(&sha, regRsp.keyHandleCertSig, regRsp.keyHandleLen);	// hk
	SHA256_update(&sha, &regRsp.pubKey, sizeof(regRsp.pubKey));	// pk
	hash = SHA256_final(&sha);
	p256_from_bin(hash, &h);

	INFO << "hash : " << bytes2ascii((char *)hash, 32);

	// Parse subject public key into two integers.
	CHECK_EQ(pk.size(), P256_POINT_SIZE, "Public key does not match P256 point size.");
	p256_int pk_x, pk_y;
	p256_from_bin((uint8_t *) pk.data() + 1, &pk_x);
	p256_from_bin((uint8_t *) pk.data() + 1 + P256_SCALAR_SIZE, &pk_y);

	// Verify signature.
	CHECK_EQ(1, p256_ecdsa_verify(&pk_x, &pk_y, &h, &sig_r, &sig_s), "Signature does not match.");

	return ReturnValue::BLEAPI_ERROR_SUCCESS;
}