/** * Unpacks the ASN.1 DSA signature sequence. */ int dsa_sig_unpack(unsigned char* sig, int sig_len, p256_int* r_int, p256_int* s_int) { /* * Structure is: * 0x30 0xNN SEQUENCE + s_length * 0x02 0xNN INTEGER + r_length * 0xAA 0xBB .. r_length bytes of "r" (offset 4) * 0x02 0xNN INTEGER + s_length * 0xMM 0xNN .. s_length bytes of "s" (offset 6 + r_len) */ int seq_len; unsigned char r_bytes[P256_NBYTES]; unsigned char s_bytes[P256_NBYTES]; int r_len; int s_len; memset(r_bytes, 0, sizeof(r_bytes)); memset(s_bytes, 0, sizeof(s_bytes)); /* * Must have at least: * 2 bytes sequence header and length * 2 bytes R integer header and length * 1 byte of R * 2 bytes S integer header and length * 1 byte of S * * 8 bytes total */ if (sig_len < 8 || sig[0] != 0x30 || sig[2] != 0x02) { return 0; } seq_len = sig[1]; if ((seq_len <= 0) || (seq_len + 2 != sig_len)) { return 0; } r_len = sig[3]; /* * Must have at least: * 2 bytes for R header and length * 2 bytes S integer header and length * 1 byte of S */ if ((r_len < 1) || (r_len > seq_len - 5) || (sig[4 + r_len] != 0x02)) { return 0; } s_len = sig[5 + r_len]; /** * Must have: * 2 bytes for R header and length * r_len bytes for R * 2 bytes S integer header and length */ if ((s_len < 1) || (s_len != seq_len - 4 - r_len)) { return 0; } /* * ASN.1 encoded integers are zero-padded for positive integers. Make sure we have * a correctly-sized buffer and that the resulting integer isn't too large. */ if (!trim_to_p256_bytes(r_bytes, &sig[4], r_len) || !trim_to_p256_bytes(s_bytes, &sig[6 + r_len], s_len)) { return 0; } p256_from_bin(r_bytes, r_int); p256_from_bin(s_bytes, s_int); return 1; }
// Reads a file containing one or more public keys as produced by // DumpPublicKey: this is an RSAPublicKey struct as it would appear // as a C source literal, eg: // // "{64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}" // // For key versions newer than the original 2048-bit e=3 keys // supported by Android, the string is preceded by a version // identifier, eg: // // "v2 {64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}" // // (Note that the braces and commas in this example are actual // characters the parser expects to find in the file; the ellipses // indicate more numbers omitted from this example.) // // The file may contain multiple keys in this format, separated by // commas. The last key must not be followed by a comma. // // A Certificate is a pair of an RSAPublicKey and a particular hash // (we support SHA-1 and SHA-256; we store the hash length to signify // which is being used). The hash used is implied by the version number. // // 1: 2048-bit RSA key with e=3 and SHA-1 hash // 2: 2048-bit RSA key with e=65537 and SHA-1 hash // 3: 2048-bit RSA key with e=3 and SHA-256 hash // 4: 2048-bit RSA key with e=65537 and SHA-256 hash // 5: 256-bit EC key using the NIST P-256 curve parameters and SHA-256 hash // // Returns NULL if the file failed to parse, or if it contain zero keys. Certificate* load_keys(const char* filename, int* numKeys) { Certificate* out = NULL; *numKeys = 0; FILE* f = fopen(filename, "r"); if (f == NULL) { LOGE("opening %s: %s\n", filename, strerror(errno)); goto exit; } { int i; bool done = false; while (!done) { ++*numKeys; out = (Certificate*)realloc(out, *numKeys * sizeof(Certificate)); Certificate* cert = out + (*numKeys - 1); memset(cert, '\0', sizeof(Certificate)); char start_char; if (fscanf(f, " %c", &start_char) != 1) goto exit; if (start_char == '{') { // a version 1 key has no version specifier. cert->key_type = Certificate::RSA; cert->rsa = (RSAPublicKey*)malloc(sizeof(RSAPublicKey)); cert->rsa->exponent = 3; cert->hash_len = SHA_DIGEST_SIZE; } else if (start_char == 'v') { int version; if (fscanf(f, "%d {", &version) != 1) goto exit; switch (version) { case 2: cert->key_type = Certificate::RSA; cert->rsa = (RSAPublicKey*)malloc(sizeof(RSAPublicKey)); cert->rsa->exponent = 65537; cert->hash_len = SHA_DIGEST_SIZE; break; case 3: cert->key_type = Certificate::RSA; cert->rsa = (RSAPublicKey*)malloc(sizeof(RSAPublicKey)); cert->rsa->exponent = 3; cert->hash_len = SHA256_DIGEST_SIZE; break; case 4: cert->key_type = Certificate::RSA; cert->rsa = (RSAPublicKey*)malloc(sizeof(RSAPublicKey)); cert->rsa->exponent = 65537; cert->hash_len = SHA256_DIGEST_SIZE; break; case 5: cert->key_type = Certificate::EC; cert->ec = (ECPublicKey*)calloc(1, sizeof(ECPublicKey)); cert->hash_len = SHA256_DIGEST_SIZE; break; default: goto exit; } } if (cert->key_type == Certificate::RSA) { RSAPublicKey* key = cert->rsa; if (fscanf(f, " %i , 0x%x , { %u", &(key->len), &(key->n0inv), &(key->n[0])) != 3) { goto exit; } if (key->len != RSANUMWORDS) { LOGE("key length (%d) does not match expected size\n", key->len); goto exit; } for (i = 1; i < key->len; ++i) { if (fscanf(f, " , %u", &(key->n[i])) != 1) goto exit; } if (fscanf(f, " } , { %u", &(key->rr[0])) != 1) goto exit; for (i = 1; i < key->len; ++i) { if (fscanf(f, " , %u", &(key->rr[i])) != 1) goto exit; } fscanf(f, " } } "); LOGI("read key e=%d hash=%d\n", key->exponent, cert->hash_len); } else if (cert->key_type == Certificate::EC) { ECPublicKey* key = cert->ec; int key_len; unsigned int byte; uint8_t x_bytes[P256_NBYTES]; uint8_t y_bytes[P256_NBYTES]; if (fscanf(f, " %i , { %u", &key_len, &byte) != 2) goto exit; if (key_len != P256_NBYTES) { LOGE("Key length (%d) does not match expected size %d\n", key_len, P256_NBYTES); goto exit; } x_bytes[P256_NBYTES - 1] = byte; for (i = P256_NBYTES - 2; i >= 0; --i) { if (fscanf(f, " , %u", &byte) != 1) goto exit; x_bytes[i] = byte; } if (fscanf(f, " } , { %u", &byte) != 1) goto exit; y_bytes[P256_NBYTES - 1] = byte; for (i = P256_NBYTES - 2; i >= 0; --i) { if (fscanf(f, " , %u", &byte) != 1) goto exit; y_bytes[i] = byte; } fscanf(f, " } } "); p256_from_bin(x_bytes, &key->x); p256_from_bin(y_bytes, &key->y); } else { LOGE("Unknown key type %d\n", cert->key_type); goto exit; } // if the line ends in a comma, this file has more keys. switch (fgetc(f)) { case ',': // more keys to come. break; case EOF: done = true; break; default: LOGE("unexpected character between keys\n"); goto exit; } } } fclose(f); return out; exit: if (f) fclose(f); free(out); *numKeys = 0; return NULL; }
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; }
// 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; }
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(®Rsp, 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, ®Rsp.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; }