29 #include "ndn-cxx/security/pib/impl/pib-memory.hpp" 30 #include "ndn-cxx/security/pib/impl/pib-sqlite3.hpp" 32 #include "ndn-cxx/security/tpm/impl/back-end-file.hpp" 33 #include "ndn-cxx/security/tpm/impl/back-end-mem.hpp" 34 #ifdef NDN_CXX_HAVE_OSX_FRAMEWORKS 35 #include "ndn-cxx/security/tpm/impl/back-end-osx.hpp" 36 #endif // NDN_CXX_HAVE_OSX_FRAMEWORKS 44 #include <boost/lexical_cast.hpp> 59 #if defined(NDN_CXX_HAVE_OSX_FRAMEWORKS) && defined(NDN_CXX_WITH_OSX_KEYCHAIN) 61 #endif // defined(NDN_CXX_HAVE_OSX_FRAMEWORKS) && defined(NDN_CXX_WITH_OSX_KEYCHAIN) 70 std::string KeyChain::s_defaultPibLocator;
71 std::string KeyChain::s_defaultTpmLocator;
73 KeyChain::PibFactories&
74 KeyChain::getPibFactories()
76 static PibFactories pibFactories;
80 KeyChain::TpmFactories&
81 KeyChain::getTpmFactories()
83 static TpmFactories tpmFactories;
88 KeyChain::getDefaultPibScheme()
90 return pib::PibSqlite3::getScheme();
94 KeyChain::getDefaultTpmScheme()
96 #if defined(NDN_CXX_HAVE_OSX_FRAMEWORKS) && defined(NDN_CXX_WITH_OSX_KEYCHAIN) 97 return tpm::BackEndOsx::getScheme();
99 return tpm::BackEndFile::getScheme();
100 #endif // defined(NDN_CXX_HAVE_OSX_FRAMEWORKS) && defined(NDN_CXX_WITH_OSX_KEYCHAIN) 104 KeyChain::getDefaultPibLocator()
106 if (!s_defaultPibLocator.empty())
107 return s_defaultPibLocator;
109 if (getenv(
"NDN_CLIENT_PIB") !=
nullptr) {
110 s_defaultPibLocator = getenv(
"NDN_CLIENT_PIB");
114 s_defaultPibLocator = config.getParsedConfiguration().get<std::string>(
"pib", getDefaultPibScheme() +
":");
117 std::string pibScheme, pibLocation;
118 std::tie(pibScheme, pibLocation) = parseAndCheckPibLocator(s_defaultPibLocator);
119 s_defaultPibLocator = pibScheme +
":" + pibLocation;
121 return s_defaultPibLocator;
125 KeyChain::getDefaultTpmLocator()
127 if (!s_defaultTpmLocator.empty())
128 return s_defaultTpmLocator;
130 if (getenv(
"NDN_CLIENT_TPM") !=
nullptr) {
131 s_defaultTpmLocator = getenv(
"NDN_CLIENT_TPM");
135 s_defaultTpmLocator = config.getParsedConfiguration().get<std::string>(
"tpm", getDefaultTpmScheme() +
":");
138 std::string tpmScheme, tpmLocation;
139 std::tie(tpmScheme, tpmLocation) = parseAndCheckTpmLocator(s_defaultTpmLocator);
140 s_defaultTpmLocator = tpmScheme +
":" + tpmLocation;
142 return s_defaultTpmLocator;
165 :
KeyChain(getDefaultPibLocator(), getDefaultTpmLocator(), true)
172 std::string pibScheme, pibLocation;
173 std::tie(pibScheme, pibLocation) = parseAndCheckPibLocator(pibLocator);
174 std::string canonicalPibLocator = pibScheme +
":" + pibLocation;
177 m_pib = createPib(canonicalPibLocator);
178 std::string oldTpmLocator;
180 oldTpmLocator = m_pib->getTpmLocator();
187 std::string tpmScheme, tpmLocation;
188 std::tie(tpmScheme, tpmLocation) = parseAndCheckTpmLocator(tpmLocator);
189 std::string canonicalTpmLocator = tpmScheme +
":" + tpmLocation;
191 if (canonicalPibLocator == getDefaultPibLocator()) {
193 if (!oldTpmLocator.empty() && oldTpmLocator != getDefaultTpmLocator()) {
195 canonicalTpmLocator = getDefaultTpmLocator();
200 if (!oldTpmLocator.empty() && oldTpmLocator != canonicalTpmLocator) {
205 oldTpmLocator +
" != " + canonicalTpmLocator));
212 m_tpm = createTpm(canonicalTpmLocator);
213 m_pib->setTpmLocator(canonicalTpmLocator);
223 Identity id = m_pib->addIdentity(identityName);
227 key =
id.getDefaultKey();
247 BOOST_ASSERT(static_cast<bool>(identity));
251 for (
const auto& key : identity.
getKeys()) {
252 m_tpm->deleteKey(key.getName());
255 m_pib->removeIdentity(identityName);
261 BOOST_ASSERT(static_cast<bool>(identity));
263 m_pib->setDefaultIdentity(identity.
getName());
269 BOOST_ASSERT(static_cast<bool>(identity));
272 Name keyName = m_tpm->createKey(identity.
getName(), params);
276 Key key = identity.addKey(pubKey->data(), pubKey->size(), keyName);
287 return m_tpm->createKey(prefix, params);
293 BOOST_ASSERT(static_cast<bool>(identity));
294 BOOST_ASSERT(static_cast<bool>(key));
299 "does not match key `" + keyName.
toUri() +
"`"));
302 identity.removeKey(keyName);
303 m_tpm->deleteKey(keyName);
309 BOOST_ASSERT(static_cast<bool>(identity));
310 BOOST_ASSERT(static_cast<bool>(key));
316 identity.setDefaultKey(key.
getName());
322 BOOST_ASSERT(static_cast<bool>(key));
328 "does not match certificate `" + certificate.
getName().
toUri() +
"`"));
330 key.addCertificate(certificate);
336 BOOST_ASSERT(static_cast<bool>(key));
339 NDN_THROW(std::invalid_argument(
"Wrong certificate name `" + certificateName.
toUri() +
"`"));
342 key.removeCertificate(certificateName);
348 BOOST_ASSERT(static_cast<bool>(key));
351 key.setDefaultCertificate(cert.
getName());
362 encryptedKey = m_tpm->exportPrivateKey(keyName, pw, pwLen);
368 return make_shared<SafeBag>(certificate, *encryptedKey);
380 if (m_tpm->hasKey(keyName)) {
385 Identity existingId = m_pib->getIdentity(identity);
386 existingId.
getKey(keyName);
394 m_tpm->importPrivateKey(keyName,
403 const uint8_t content[] = {0x01, 0x02, 0x03, 0x04};
408 catch (
const std::runtime_error&) {
409 m_tpm->deleteKey(keyName);
412 bool isVerified =
false;
414 using namespace transform;
416 publicKey.loadPkcs8(publicKeyBits.data(), publicKeyBits.size());
418 sigBits->data(), sigBits->size())
422 m_tpm->deleteKey(keyName);
424 "and private key `" + keyName.
toUri() +
"` do not match"));
427 Identity id = m_pib->addIdentity(identity);
429 key.addCertificate(cert);
435 if (m_tpm->hasKey(keyName)) {
440 m_tpm->importPrivateKey(keyName,
std::move(key));
454 std::tie(keyName, sigInfo) = prepareSignatureInfo(params);
471 std::tie(keyName, sigInfo) = prepareSignatureInfo(params);
480 signedName.
append(sigValue);
489 std::tie(keyName, sigInfo) = prepareSignatureInfo(params);
496 static inline std::tuple<std::string, std::string>
499 size_t pos = uri.find(
':');
500 if (pos != std::string::npos) {
501 return std::make_tuple(uri.substr(0, pos), uri.substr(pos + 1));
504 return std::make_tuple(uri,
"");
508 std::tuple<std::string, std::string>
509 KeyChain::parseAndCheckPibLocator(
const std::string& pibLocator)
511 std::string pibScheme, pibLocation;
514 if (pibScheme.empty()) {
515 pibScheme = getDefaultPibScheme();
518 auto pibFactory = getPibFactories().find(pibScheme);
519 if (pibFactory == getPibFactories().end()) {
523 return std::make_tuple(pibScheme, pibLocation);
527 KeyChain::createPib(
const std::string& pibLocator)
529 std::string pibScheme, pibLocation;
530 std::tie(pibScheme, pibLocation) = parseAndCheckPibLocator(pibLocator);
531 auto pibFactory = getPibFactories().find(pibScheme);
532 BOOST_ASSERT(pibFactory != getPibFactories().end());
533 return unique_ptr<Pib>(
new Pib(pibScheme, pibLocation, pibFactory->second(pibLocation)));
536 std::tuple<std::string, std::string>
537 KeyChain::parseAndCheckTpmLocator(
const std::string& tpmLocator)
539 std::string tpmScheme, tpmLocation;
542 if (tpmScheme.empty()) {
543 tpmScheme = getDefaultTpmScheme();
545 auto tpmFactory = getTpmFactories().find(tpmScheme);
546 if (tpmFactory == getTpmFactories().end()) {
550 return std::make_tuple(tpmScheme, tpmLocation);
554 KeyChain::createTpm(
const std::string& tpmLocator)
556 std::string tpmScheme, tpmLocation;
557 std::tie(tpmScheme, tpmLocation) = parseAndCheckTpmLocator(tpmLocator);
558 auto tpmFactory = getTpmFactories().find(tpmScheme);
559 BOOST_ASSERT(tpmFactory != getTpmFactories().end());
560 return unique_ptr<Tpm>(
new Tpm(tpmScheme, tpmLocation, tpmFactory->second(tpmLocation)));
566 KeyChain::selfSign(
Key& key)
575 certificate.
setName(certificateName);
593 key.addCertificate(certificate);
597 std::tuple<Name, SignatureInfo>
598 KeyChain::prepareSignatureInfo(
const SigningInfo& params)
607 identity = m_pib->getDefaultIdentity();
647 identity = m_pib->getIdentity(identityName);
648 key = identity.
getKey(keyName);
663 if (!m_tpm->hasKey(keyName)) {
664 m_tpm->importPrivateKey(keyName, params.
getHmacKey());
669 return std::make_tuple(keyName, sigInfo);
672 NDN_THROW(InvalidSigningInfoError(
"Unrecognized signer type " +
679 NDN_THROW(InvalidSigningInfoError(
"Cannot determine signing parameters"));
686 "` does not have a default certificate"));
696 return std::make_tuple(key.
getName(), sigInfo);
720 NDN_THROW(Error(
"Unsupported key type " + boost::lexical_cast<std::string>(keyType)));
#define NDN_THROW_NESTED(e)
void deleteKey(const Identity &identity, const Key &key)
Delete a key key of identity.
Key getKey(const Name &keyName) const
Get a key with id keyName.
Data & setContentType(uint32_t type)
void setSignatureType(tlv::SignatureTypeValue type)
Set SignatureType.
The certificate following the certificate format naming convention.
represents a semantic error
const Name & getName() const
Get name.
Buffer getPublicKey() const
Get public key bits (in PKCS#8 format)
Represents a SignatureInfo TLV element.
The interface of signing key management.
const SignatureInfo & getSignatureInfo() const
SimpleSymmetricKeyParams is a template for symmetric keys with only one parameter: size...
void addCertificate(const Key &key, const Certificate &certificate)
Add a certificate certificate for key.
const Block & getContent() const
Get Content.
Key createKey(const Identity &identity, const KeyParams ¶ms=getDefaultKeyParams())
Create a new key for identity.
Name getIdentity() const
Get identity name.
Data & setSignature(const Signature &signature)
Set Signature.
Data & setName(const Name &name)
Set name.
DigestAlgorithm getDigestAlgorithm() const
KeyType getKeyType() const
Get key type.
Name extractKeyNameFromCertName(const Name &certName)
Extract key name from the certificate name certName.
static std::tuple< std::string, std::string > parseLocatorUri(const std::string &uri)
RSA key, supports sign/verify and encrypt/decrypt operations.
KeyChain()
Constructor to create KeyChain with default PIB and TPM.
Data & setContent(const Block &block)
Set Content from a block.
const Key & getPibKey() const
Represents a TLV element of NDN packet format.
Error indicating that the supplied TPM locator does not match the locator stored in PIB...
Represents an Interest packet.
#define NDN_LOG_DEBUG(expression)
Log at DEBUG level.
Use a SHA-256 digest only, no signer needs to be specified.
shared_ptr< transform::PrivateKey > getHmacKey() const
#define NDN_LOG_INIT(name)
Define a non-member log module.
static time_point now() noexcept
Name & append(const Component &component)
Append a component.
Signing parameters passed to KeyChain.
void deleteCertificate(const Key &key, const Name &certificateName)
delete a certificate with name certificateName of key.
Name & appendVersion(optional< uint64_t > version=nullopt)
Append a version component.
const Buffer & getEncryptedKeyBag() const
Get the private key in PKCS#8 from safe bag.
#define NDN_CXX_V2_KEYCHAIN_REGISTER_PIB_BACKEND(PibType)
Register Pib backend class in KeyChain.
HMAC key, supports sign/verify operations.
Buffer::const_iterator value_begin() const
Get begin iterator of TLV-VALUE.
Identity createIdentity(const Name &identityName, const KeyParams ¶ms=getDefaultKeyParams())
Create an identity identityName.
void importSafeBag(const SafeBag &safeBag, const char *pw, size_t pwLen)
Import a certificate and its corresponding private key from a SafeBag.
const Name & getSignerName() const
KeyType
The type of a cryptographic key.
void setKeyLocator(const KeyLocator &keyLocator)
Set KeyLocator.
size_t wireEncode(EncodingImpl< TAG > &encoder) const
Fast encoding or block size estimation.
shared_ptr< SafeBag > exportSafeBag(const Certificate &certificate, const char *pw, size_t pwLen)
Export a certificate and its corresponding private key.
const Data & getCertificate() const
Get the certificate data packet from safe bag.
A frontend handle of a key instance.
No signer is specified, use default setting or follow the trust schema.
void setDefaultCertificate(const Key &key, const Certificate &certificate)
Set cert as the default certificate of key.
void setDefaultIdentity(const Identity &identity)
Set identity as the default identity.
Name getKeyName() const
Get key name.
Buffer::const_iterator value_end() const
Get end iterator of TLV-VALUE.
static const SigningInfo & getDefaultSigningInfo()
Elliptic Curve key (e.g. for ECDSA), supports sign/verify operations.
static const Name & getDigestSha256Identity()
A localhost identity to indicate that the signature is generated using SHA-256.
void setValidityPeriod(const security::ValidityPeriod &validityPeriod)
Set ValidityPeriod.
Use the SHA256 hash of the public key as key id.
Represents an absolute name.
const Name & getName() const
Get key name.
Signer is a certificate, use it directly.
Name createHmacKey(const Name &prefix=SigningInfo::getHmacIdentity(), const HmacKeyParams ¶ms=HmacKeyParams())
Create a new HMAC key.
void importPrivateKey(const Name &keyName, shared_ptr< transform::PrivateKey > key)
Import a private key into the TPM.
SignatureTypeValue
SignatureType values.
Signer is a key, use its default certificate.
void sign(Data &data, const SigningInfo ¶ms=getDefaultSigningInfo())
Sign data according to the supplied signing information.
const Identity & getPibIdentity() const
const Key & getDefaultKey() const
Get the default key for this Identity.
void deleteIdentity(const Identity &identity)
delete identity.
static bool isValidName(const Name &certName)
Check if the specified name follows the naming convention for the certificate.
static const KeyParams & getDefaultKeyParams()
a secured container for sensitive information(certificate, private key)
Data & setFreshnessPeriod(time::milliseconds freshnessPeriod)
void setDefaultKey(const Identity &identity, const Key &key)
Set key as the default key of identity.
void encode()
Encode sub-elements into TLV-VALUE.
const Name & getName() const noexcept
const Name & getName() const
Get the name of the identity.
const v2::Certificate & getDefaultCertificate() const
Get the default certificate for this Key.
size_t wireEncode(EncodingImpl< TAG > &encoder, bool wantUnsignedPortionOnly=false) const
Prepend wire encoding to encoder in NDN Packet Format v0.2.
Base class for key parameters.
void toUri(std::ostream &os, name::UriFormat format=name::UriFormat::DEFAULT) const
Write URI representation of the name to the output stream.
Signer is an identity, use its default key and default certificate.
const Buffer & getPublicKey() const
Get public key bits.
A frontend handle of an Identity.
ConstBufferPtr computeDigest()
Finalize and return the digest based on all previously supplied inputs.
size_t wireEncode(EncodingImpl< TAG > &encoder) const
Fast encoding or block size estimation.
const KeyContainer & getKeys() const
Get all keys for this identity.
#define NDN_LOG_TRACE(expression)
Log at TRACE level.
Represents a Data packet.
SimplePublicKeyParams is a template for public keys with only one parameter: size.
Name extractIdentityFromKeyName(const Name &keyName)
Extract identity namespace from the key name keyName.
General-purpose automatically managed/resized buffer.
const Name & getIdentity() const
Get the name of the belonging identity.
EncodingImpl< EncoderTag > EncodingBuffer
#define NDN_CXX_V2_KEYCHAIN_REGISTER_TPM_BACKEND(TpmType)
Register Tpm backend class in KeyChain.
SignerType getSignerType() const
Holds SignatureInfo and SignatureValue in a Data packet.
shared_ptr< const Buffer > ConstBufferPtr
Interest & setName(const Name &name)
Set the Interest's name.
Name extractIdentityFromCertName(const Name &certName)
Extract identity namespace from the certificate name certName.