') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); Hal review comment fixes by AvinashHedage · Pull Request #164 · divegeek/JavaCardKeymaster · GitHub
Skip to content
This repository was archived by the owner on May 24, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
360 changes: 164 additions & 196 deletions HAL/CborConverter.cpp

Large diffs are not rendered by default.

126 changes: 56 additions & 70 deletions HAL/CborConverter.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,18 +15,22 @@
** limitations under the License.
*/
#pragma once
#include <aidl/android/hardware/security/keymint/Certificate.h>
#include <aidl/android/hardware/security/keymint/IKeyMintDevice.h>
#include <aidl/android/hardware/security/secureclock/TimeStampToken.h>
#include <aidl/android/hardware/security/sharedsecret/ISharedSecret.h>
#include <cppbor.h>
#include <cppbor_parse.h>

#include <iostream>
#include <keymaster/android_keymaster_messages.h>
#include <memory>
#include <numeric>
#include <vector>

#include <cppbor.h>
#include <cppbor_parse.h>

#include <aidl/android/hardware/security/keymint/Certificate.h>
#include <aidl/android/hardware/security/keymint/IKeyMintDevice.h>
#include <aidl/android/hardware/security/sharedsecret/ISharedSecret.h>
#include <aidl/android/hardware/security/secureclock/TimeStampToken.h>

#include <keymaster/android_keymaster_messages.h>

namespace keymint::javacard {
using namespace cppbor;
using namespace aidl::android::hardware::security::keymint;
Expand All@@ -44,22 +48,35 @@ class CborConverter {
decodeData(const std::vector<uint8_t>& response);

template <typename T>
bool getUint64(const std::unique_ptr<Item>& item, const uint32_t pos, T& value);

template <typename T> bool getUint64(const std::unique_ptr<Item>& item, T& value);
std::optional<T> getUint64(const unique_ptr<Item> &item) {
T value;
if ((item == nullptr) || (std::is_unsigned<T>::value && (MajorType::UINT != getType(item))) ||
((std::is_signed<T>::value && (MajorType::NINT != getType(item))))) {
return std::nullopt;
}
if (std::is_unsigned<T>::value) {
const Uint *uintVal = item.get()->asUint();
value = static_cast<T>(uintVal->value());
} else {
const Nint *nintVal = item.get()->asNint();
value = static_cast<T>(nintVal->value());
}
return value; // success
}

bool getSharedSecretParameters(const std::unique_ptr<Item>& item, const uint32_t pos,
SharedSecretParameters& params);
bool getBinaryArray(const std::unique_ptr<Item>& item, const uint32_t pos, string& value);
template <typename T>
std::optional<T> getUint64(const unique_ptr<Item> &item, const uint32_t pos) {
auto intItem = getItemAtPos(item, pos);
return getUint64<T>(intItem.value());
}

bool getBinaryArray(const std::unique_ptr<Item>& item, const uint32_t pos,
vector<uint8_t>& value);
std::optional<SharedSecretParameters> getSharedSecretParameters(const std::unique_ptr<Item>& item, const uint32_t pos);

std::optional<string> getByteArrayStr(const unique_ptr<Item>& item, const uint32_t pos);

bool getHardwareAuthToken(const std::unique_ptr<Item>& item, const uint32_t pos,
HardwareAuthToken& authType);
std::optional<std::vector<uint8_t>> getByteArrayVec(const unique_ptr<Item>& item, const uint32_t pos);

bool getKeyParameters(const std::unique_ptr<Item>& item, const uint32_t pos,
vector<KeyParameter>& keyParams);
std::optional<vector<KeyParameter>> getKeyParameters(const unique_ptr<Item>& item, const uint32_t pos);

bool addKeyparameters(Array& array, const vector<KeyParameter>& keyParams);

Expand All@@ -69,34 +86,27 @@ class CborConverter {

bool addSharedSecretParameters(Array& array, const vector<SharedSecretParameters>& params);

bool getTimeStampToken(const std::unique_ptr<Item>& item, const uint32_t pos,
TimeStampToken& token);
std::optional<TimeStampToken> getTimeStampToken(const std::unique_ptr<Item>& item, const uint32_t pos);

bool getKeyCharacteristics(const std::unique_ptr<Item>& item, const uint32_t pos,
vector<KeyCharacteristics>& keyCharacteristics);
std::optional<vector<KeyCharacteristics>> getKeyCharacteristics(const std::unique_ptr<Item>& item, const uint32_t pos);

bool getCertificateChain(const std::unique_ptr<Item>& item, const uint32_t pos,
vector<Certificate>& keyCharacteristics);
std::optional<vector<Certificate>> getCertificateChain(const std::unique_ptr<Item>& item, const uint32_t pos);

bool getMultiBinaryArray(const std::unique_ptr<Item>& item, const uint32_t pos,
vector<vector<uint8_t>>& data);
std::optional<vector<vector<uint8_t>>> getMultiByteArray(const unique_ptr<Item>& item, const uint32_t pos);

bool addTimeStampToken(Array& array, const TimeStampToken& token);

bool getMapItem(const std::unique_ptr<Item>& item, const uint32_t pos,
Map& map);
std::optional<Map> getMapItem(const std::unique_ptr<Item>& item, const uint32_t pos);

bool getArrayItem(const std::unique_ptr<Item>& item, const uint32_t pos,
Array& array);

inline bool getErrorCode(const std::unique_ptr<Item>& item, const uint32_t pos,
keymaster_error_t& errorCode) {
uint64_t errorVal;
if (!getUint64<uint64_t>(item, pos, errorVal)) {
return false;
std::optional<Array> getArrayItem(const std::unique_ptr<Item>& item, const uint32_t pos);

inline std::optional<keymaster_error_t> getErrorCode(const std::unique_ptr<Item>& item, const uint32_t pos) {

auto optErrorVal = getUint64<uint64_t>(item, pos);
if (!optErrorVal) {
return std::nullopt;
}
errorCode = static_cast<keymaster_error_t>(0 - errorVal);
return true;
return static_cast<keymaster_error_t>(0 - optErrorVal.value());
}

private:
Expand All@@ -115,49 +125,25 @@ class CborConverter {
* value contains binary string. If TagType is UINT_REP or ULONG_REP the value contains Array of
* unsigned integers.
*/
bool getKeyParameter(const std::pair<const unique_ptr<Item>&, const unique_ptr<Item>&> pair,
vector<KeyParameter>& keyParam);
std::optional<std::vector<KeyParameter>>
getKeyParameter(const std::pair<const std::unique_ptr<Item>&,
const std::unique_ptr<Item>&> pair);

/**
* Get the sub item pointer from the root item pointer at the given position.
*/
inline void getItemAtPos(const unique_ptr<Item>& item, const uint32_t pos,
unique_ptr<Item>& subItem) {
inline std::optional<unique_ptr<Item>> getItemAtPos(const unique_ptr<Item>& item, const uint32_t pos) {
Array* arr = nullptr;

if (MajorType::ARRAY != getType(item)) {
return;
return std::nullopt;
}
arr = const_cast<Array*>(item.get()->asArray());
if (arr->size() < (pos + 1)) {
return;
return std::nullopt;
}
subItem = std::move((*arr)[pos]);
return std::move((*arr)[pos]);
}
};

template <typename T> bool CborConverter::getUint64(const unique_ptr<Item>& item, T& value) {
bool ret = false;
if ((item == nullptr) || (std::is_unsigned<T>::value && (MajorType::UINT != getType(item))) ||
((std::is_signed<T>::value && (MajorType::NINT != getType(item))))) {
return ret;
}

if (std::is_unsigned<T>::value) {
const Uint* uintVal = item.get()->asUint();
value = static_cast<T>(uintVal->value());
} else {
const Nint* nintVal = item.get()->asNint();
value = static_cast<T>(nintVal->value());
}
ret = true;
return ret; // success
}

template <typename T>
bool CborConverter::getUint64(const unique_ptr<Item>& item, const uint32_t pos, T& value) {
unique_ptr<Item> intItem(nullptr);
getItemAtPos(item, pos, intItem);
return getUint64(intItem, value);
}
} // namespace keymint::javacard
2 changes: 2 additions & 0 deletions HAL/ITransport.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,8 +15,10 @@
** limitations under the License.
*/
#pragma once

#include <memory>
#include <vector>

#include <hardware/keymaster_defs.h>

namespace keymint::javacard {
Expand Down
107 changes: 66 additions & 41 deletions HAL/JavacardKeyMintDevice.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,23 +15,28 @@
*/

#define LOG_TAG "javacard.keymint.device.strongbox-impl"

#include "JavacardKeyMintDevice.h"
#include "JavacardKeyMintOperation.h"
#include "JavacardSharedSecret.h"
#include <JavacardKeyMintUtils.h>

#include <regex.h>

#include <algorithm>
#include <android-base/logging.h>
#include <android-base/properties.h>
#include <hardware/hw_auth_token.h>
#include <iostream>
#include <iterator>
#include <keymaster/android_keymaster_messages.h>
#include <keymaster/wrapped_key.h>
#include <memory>
#include <regex.h>
#include <string>
#include <vector>

#include <android-base/logging.h>
#include <android-base/properties.h>
#include <hardware/hw_auth_token.h>
#include <keymaster/android_keymaster_messages.h>
#include <keymaster/wrapped_key.h>

#include "JavacardKeyMintOperation.h"
#include "JavacardKeyMintUtils.h"
#include "JavacardSharedSecret.h"

namespace aidl::android::hardware::security::keymint {
using km_utils::KmParamSet;
using namespace ::keymaster;
Expand All@@ -48,24 +53,28 @@ ScopedAStatus JavacardKeyMintDevice::defaultHwInfo(KeyMintHardwareInfo* info) {


ScopedAStatus JavacardKeyMintDevice::getHardwareInfo(KeyMintHardwareInfo* info) {
uint64_t tsRequired = 1;
auto [item, err] = card_->sendRequest(Instruction::INS_GET_HW_INFO_CMD);
uint32_t secLevel;
uint32_t version;
if (err != KM_ERROR_OK || !cbor_.getUint64<uint32_t>(item, 1, version) ||
!cbor_.getUint64<uint32_t>(item, 2, secLevel) ||
!cbor_.getBinaryArray(item, 3, info->keyMintName) ||
!cbor_.getBinaryArray(item, 4, info->keyMintAuthorName) ||
!cbor_.getUint64<uint64_t>(item, 5, tsRequired)) {
std::optional<string> optKeyMintName;
std::optional<string> optKeyMintAuthorName;
std::optional<uint32_t> optSecLevel;
std::optional<uint32_t> optVersion;
std::optional<uint64_t> optTsRequired;
if (err != KM_ERROR_OK || !(optVersion = cbor_.getUint64<uint32_t>(item, 1)) ||
!(optSecLevel = cbor_.getUint64<uint32_t>(item, 2)) ||
!(optKeyMintName = cbor_.getByteArrayStr(item, 3)) ||
!(optKeyMintAuthorName = cbor_.getByteArrayStr(item, 4)) ||
!(optTsRequired = cbor_.getUint64<uint64_t>(item, 5))) {
// TODO should we return HARDWARE_NOT_YET_AVAILABLE instead of default Hardware Info.
LOG(ERROR) << "Error in response of getHardwareInfo.";
LOG(INFO) << "Returning defaultHwInfo in getHardwareInfo.";
return defaultHwInfo(info);
}
card_->initializeJavacard();
info->timestampTokenRequired = (tsRequired == 1);
info->securityLevel = static_cast<SecurityLevel>(secLevel);
info->versionNumber = static_cast<int32_t>(version);
info->keyMintName = std::move(optKeyMintName.value());
info->keyMintAuthorName = std::move(optKeyMintAuthorName.value());
info->timestampTokenRequired = (optTsRequired.value() == 1);
info->securityLevel = static_cast<SecurityLevel>(std::move(optSecLevel.value()));
info->versionNumber = static_cast<int32_t>(std::move(optVersion.value()));
return ScopedAStatus::ok();
}

Expand All@@ -82,12 +91,16 @@ ScopedAStatus JavacardKeyMintDevice::generateKey(const vector<KeyParameter>& key
LOG(ERROR) << "Error in sending generateKey.";
return km_utils::kmError2ScopedAStatus(err);
}
if (!cbor_.getBinaryArray(item, 1, creationResult->keyBlob) ||
!cbor_.getKeyCharacteristics(item, 2, creationResult->keyCharacteristics) ||
!cbor_.getCertificateChain(item, 3, creationResult->certificateChain)) {
auto optKeyBlob = cbor_.getByteArrayVec(item, 1);
auto optKeyChars = cbor_.getKeyCharacteristics(item, 2);
auto optCertChain = cbor_.getCertificateChain(item, 3);
if (!optKeyBlob || !optKeyChars || !optCertChain) {
LOG(ERROR) << "Error in decoding og response in generateKey.";
return km_utils::kmError2ScopedAStatus(KM_ERROR_UNKNOWN_ERROR);
}
creationResult->keyCharacteristics = std::move(optKeyChars.value());
creationResult->certificateChain = std::move(optCertChain.value());
creationResult->keyBlob = std::move(optKeyBlob.value());
return ScopedAStatus::ok();
}

Expand DownExpand Up@@ -123,12 +136,16 @@ ScopedAStatus JavacardKeyMintDevice::importKey(const vector<KeyParameter>& keyPa
LOG(ERROR) << "Error in sending data in importKey.";
return km_utils::kmError2ScopedAStatus(err);
}
if (!cbor_.getBinaryArray(item, 1, creationResult->keyBlob) ||
!cbor_.getKeyCharacteristics(item, 2, creationResult->keyCharacteristics) ||
!cbor_.getCertificateChain(item, 3, creationResult->certificateChain)) {
auto optKeyBlob = cbor_.getByteArrayVec(item, 1);
auto optKeyChars = cbor_.getKeyCharacteristics(item, 2);
auto optCertChain = cbor_.getCertificateChain(item, 3);
if (!optKeyBlob || !optKeyChars || !optCertChain) {
LOG(ERROR) << "Error in decoding response in importKey.";
return km_utils::kmError2ScopedAStatus(KM_ERROR_UNKNOWN_ERROR);
}
creationResult->keyCharacteristics = std::move(optKeyChars.value());
creationResult->certificateChain = std::move(optCertChain.value());
creationResult->keyBlob = std::move(optKeyBlob.value());
return ScopedAStatus::ok();
}

Expand DownExpand Up@@ -172,12 +189,16 @@ ScopedAStatus JavacardKeyMintDevice::importWrappedKey(const vector<uint8_t>& wra
LOG(ERROR) << "Error in send finish import wrapped key in importWrappedKey.";
return km_utils::kmError2ScopedAStatus(errorCode);
}
if (!cbor_.getBinaryArray(item, 1, creationResult->keyBlob) ||
!cbor_.getKeyCharacteristics(item, 2, creationResult->keyCharacteristics) ||
!cbor_.getCertificateChain(item, 3, creationResult->certificateChain)) {
auto optKeyBlob = cbor_.getByteArrayVec(item, 1);
auto optKeyChars = cbor_.getKeyCharacteristics(item, 2);
auto optCertChain = cbor_.getCertificateChain(item, 3);
if (!optKeyBlob || !optKeyChars || !optCertChain) {
LOG(ERROR) << "Error in decoding the response in importWrappedKey.";
return km_utils::kmError2ScopedAStatus(KM_ERROR_UNKNOWN_ERROR);
}
creationResult->keyCharacteristics = std::move(optKeyChars.value());
creationResult->certificateChain = std::move(optCertChain.value());
creationResult->keyBlob = std::move(optKeyBlob.value());
return ScopedAStatus::ok();
}

Expand DownExpand Up@@ -225,10 +246,12 @@ ScopedAStatus JavacardKeyMintDevice::upgradeKey(const vector<uint8_t>& keyBlobTo
LOG(ERROR) << "Error in sending in upgradeKey.";
return km_utils::kmError2ScopedAStatus(err);
}
if (!cbor_.getBinaryArray(item, 1, *keyBlob)) {
auto optKeyBlob = cbor_.getByteArrayVec(item, 1);
if (!optKeyBlob) {
LOG(ERROR) << "Error in decoding the response in upgradeKey.";
return km_utils::kmError2ScopedAStatus(KM_ERROR_UNKNOWN_ERROR);
}
*keyBlob = std::move(optKeyBlob.value());
return ScopedAStatus::ok();
}

Expand DownExpand Up@@ -284,20 +307,20 @@ ScopedAStatus JavacardKeyMintDevice::begin(KeyPurpose purpose, const std::vector
return km_utils::kmError2ScopedAStatus(err);
}
// return the result
uint64_t opHandle;
uint8_t bufMode;
uint16_t macLength;
if (!cbor_.getKeyParameters(item, 1, result->params) ||
!cbor_.getUint64<uint64_t>(item, 2, opHandle) ||
!cbor_.getUint64<uint8_t>(item, 3, bufMode) ||
!cbor_.getUint64<uint16_t>(item, 4, macLength)) {
auto keyParams = cbor_.getKeyParameters(item, 1);
auto optOpHandle = cbor_.getUint64<uint64_t>(item, 2);
auto optBufMode = cbor_.getUint64<uint8_t>(item, 3);
auto optMacLength = cbor_.getUint64<uint16_t>(item, 4);

if (!keyParams || !optOpHandle || !optBufMode || !optMacLength) {
LOG(ERROR) << "Error in decoding the response in begin.";
return km_utils::kmError2ScopedAStatus(KM_ERROR_UNKNOWN_ERROR);
}
result->challenge = opHandle;
result->params = std::move(keyParams.value());
result->challenge = optOpHandle.value();
result->operation = ndk::SharedRefBase::make<JavacardKeyMintOperation>(
static_cast<keymaster_operation_handle_t>(opHandle), static_cast<BufferingMode>(bufMode),
macLength, card_);
static_cast<keymaster_operation_handle_t>(optOpHandle.value()), static_cast<BufferingMode>(optBufMode.value()),
optMacLength.value(), card_);
return ScopedAStatus::ok();
}

Expand DownExpand Up@@ -350,10 +373,12 @@ ScopedAStatus JavacardKeyMintDevice::getKeyCharacteristics(
LOG(ERROR) << "Error in sending in getKeyCharacteristics.";
return km_utils::kmError2ScopedAStatus(err);
}
if (!cbor_.getKeyCharacteristics(item, 1, *result)) {
auto optKeyChars = cbor_.getKeyCharacteristics(item, 1);
if (!optKeyChars) {
LOG(ERROR) << "Error in sending in upgradeKey.";
return km_utils::kmError2ScopedAStatus(KM_ERROR_UNKNOWN_ERROR);
}
*result = std::move(optKeyChars.value());
return ScopedAStatus::ok();
}

Expand Down
Loading