28 #include "ndn-cxx/security/pib/impl/pib-memory.hpp" 29 #include "ndn-cxx/security/pib/impl/pib-sqlite3.hpp" 31 #include "ndn-cxx/security/tpm/impl/back-end-file.hpp" 32 #include "ndn-cxx/security/tpm/impl/back-end-mem.hpp" 33 #ifdef NDN_CXX_HAVE_OSX_FRAMEWORKS 34 #include "ndn-cxx/security/tpm/impl/back-end-osx.hpp" 35 #endif // NDN_CXX_HAVE_OSX_FRAMEWORKS 45 #include <boost/lexical_cast.hpp> 60 #if defined(NDN_CXX_HAVE_OSX_FRAMEWORKS) && defined(NDN_CXX_WITH_OSX_KEYCHAIN) 62 #endif // defined(NDN_CXX_HAVE_OSX_FRAMEWORKS) && defined(NDN_CXX_WITH_OSX_KEYCHAIN) 71 std::string KeyChain::s_defaultPibLocator;
72 std::string KeyChain::s_defaultTpmLocator;
74 KeyChain::PibFactories&
75 KeyChain::getPibFactories()
77 static PibFactories pibFactories;
81 KeyChain::TpmFactories&
82 KeyChain::getTpmFactories()
84 static TpmFactories tpmFactories;
89 KeyChain::getDefaultPibScheme()
91 return pib::PibSqlite3::getScheme();
95 KeyChain::getDefaultTpmScheme()
97 #if defined(NDN_CXX_HAVE_OSX_FRAMEWORKS) && defined(NDN_CXX_WITH_OSX_KEYCHAIN) 98 return tpm::BackEndOsx::getScheme();
100 return tpm::BackEndFile::getScheme();
101 #endif // defined(NDN_CXX_HAVE_OSX_FRAMEWORKS) && defined(NDN_CXX_WITH_OSX_KEYCHAIN) 105 KeyChain::getDefaultPibLocator()
107 if (!s_defaultPibLocator.empty())
108 return s_defaultPibLocator;
110 if (getenv(
"NDN_CLIENT_PIB") !=
nullptr) {
111 s_defaultPibLocator = getenv(
"NDN_CLIENT_PIB");
115 s_defaultPibLocator = config.
getParsedConfiguration().get<std::string>(
"pib", getDefaultPibScheme() +
":");
118 std::string pibScheme, pibLocation;
119 std::tie(pibScheme, pibLocation) = parseAndCheckPibLocator(s_defaultPibLocator);
120 s_defaultPibLocator = pibScheme +
":" + pibLocation;
122 return s_defaultPibLocator;
126 KeyChain::getDefaultTpmLocator()
128 if (!s_defaultTpmLocator.empty())
129 return s_defaultTpmLocator;
131 if (getenv(
"NDN_CLIENT_TPM") !=
nullptr) {
132 s_defaultTpmLocator = getenv(
"NDN_CLIENT_TPM");
136 s_defaultTpmLocator = config.
getParsedConfiguration().get<std::string>(
"tpm", getDefaultTpmScheme() +
":");
139 std::string tpmScheme, tpmLocation;
140 std::tie(tpmScheme, tpmLocation) = parseAndCheckTpmLocator(s_defaultTpmLocator);
141 s_defaultTpmLocator = tpmScheme +
":" + tpmLocation;
143 return s_defaultTpmLocator;
166 :
KeyChain(getDefaultPibLocator(), getDefaultTpmLocator(), true)
173 std::string pibScheme, pibLocation;
174 std::tie(pibScheme, pibLocation) = parseAndCheckPibLocator(pibLocator);
175 std::string canonicalPibLocator = pibScheme +
":" + pibLocation;
178 m_pib = createPib(canonicalPibLocator);
179 std::string oldTpmLocator;
181 oldTpmLocator = m_pib->getTpmLocator();
188 std::string tpmScheme, tpmLocation;
189 std::tie(tpmScheme, tpmLocation) = parseAndCheckTpmLocator(tpmLocator);
190 std::string canonicalTpmLocator = tpmScheme +
":" + tpmLocation;
192 if (canonicalPibLocator == getDefaultPibLocator()) {
194 if (!oldTpmLocator.empty() && oldTpmLocator != getDefaultTpmLocator()) {
196 canonicalTpmLocator = getDefaultTpmLocator();
201 if (!oldTpmLocator.empty() && oldTpmLocator != canonicalTpmLocator) {
206 oldTpmLocator +
" != " + canonicalTpmLocator));
213 m_tpm = createTpm(canonicalTpmLocator);
214 m_pib->setTpmLocator(canonicalTpmLocator);
224 Identity id = m_pib->addIdentity(identityName);
228 key =
id.getDefaultKey();
248 BOOST_ASSERT(static_cast<bool>(identity));
252 for (
const auto& key : identity.
getKeys()) {
253 m_tpm->deleteKey(key.getName());
256 m_pib->removeIdentity(identityName);
262 BOOST_ASSERT(static_cast<bool>(identity));
264 m_pib->setDefaultIdentity(identity.
getName());
270 BOOST_ASSERT(static_cast<bool>(identity));
273 Name keyName = m_tpm->createKey(identity.
getName(), params);
277 Key key = identity.addKey(pubKey->data(), pubKey->size(), keyName);
288 return m_tpm->createKey(prefix, params);
294 BOOST_ASSERT(static_cast<bool>(identity));
295 BOOST_ASSERT(static_cast<bool>(key));
300 "does not match key `" + keyName.
toUri() +
"`"));
303 identity.removeKey(keyName);
304 m_tpm->deleteKey(keyName);
310 BOOST_ASSERT(static_cast<bool>(identity));
311 BOOST_ASSERT(static_cast<bool>(key));
317 identity.setDefaultKey(key.
getName());
323 BOOST_ASSERT(static_cast<bool>(key));
325 const auto& certContent = certificate.
getContent();
326 if (certContent.value_size() == 0) {
331 !std::equal(certContent.value_begin(), certContent.value_end(), key.
getPublicKey().begin())) {
333 "does not match certificate `" + certificate.
getName().
toUri() +
"`"));
336 key.addCertificate(certificate);
342 BOOST_ASSERT(static_cast<bool>(key));
345 NDN_THROW(std::invalid_argument(
"Wrong certificate name `" + certificateName.
toUri() +
"`"));
348 key.removeCertificate(certificateName);
354 BOOST_ASSERT(static_cast<bool>(key));
357 key.setDefaultCertificate(cert.
getName());
368 encryptedKey = m_tpm->exportPrivateKey(keyName, pw, pwLen);
374 return make_shared<SafeBag>(certificate, *encryptedKey);
386 if (m_tpm->hasKey(keyName)) {
391 Identity existingId = m_pib->getIdentity(identity);
392 existingId.
getKey(keyName);
400 m_tpm->importPrivateKey(keyName,
409 const uint8_t content[] = {0x01, 0x02, 0x03, 0x04};
414 catch (
const std::runtime_error&) {
415 m_tpm->deleteKey(keyName);
418 bool isVerified =
false;
420 using namespace transform;
422 publicKey.loadPkcs8(publicKeyBits.data(), publicKeyBits.size());
424 sigBits->data(), sigBits->size())
428 m_tpm->deleteKey(keyName);
430 "and private key `" + keyName.
toUri() +
"` do not match"));
433 Identity id = m_pib->addIdentity(identity);
435 key.addCertificate(cert);
441 if (m_tpm->hasKey(keyName)) {
446 m_tpm->importPrivateKey(keyName, std::move(key));
460 std::tie(keyName, sigInfo) = prepareSignatureInfo(params);
478 std::tie(keyName, sigInfo) = prepareSignatureInfo(params);
495 signedName.
append(std::move(sigValue));
505 std::tie(keyName, sigInfo) = prepareSignatureInfo(params);
513 static inline std::tuple<std::string, std::string>
516 size_t pos = uri.find(
':');
517 if (pos != std::string::npos) {
518 return std::make_tuple(uri.substr(0, pos), uri.substr(pos + 1));
521 return std::make_tuple(uri,
"");
525 std::tuple<std::string, std::string>
526 KeyChain::parseAndCheckPibLocator(
const std::string& pibLocator)
528 std::string pibScheme, pibLocation;
531 if (pibScheme.empty()) {
532 pibScheme = getDefaultPibScheme();
535 auto pibFactory = getPibFactories().find(pibScheme);
536 if (pibFactory == getPibFactories().end()) {
540 return std::make_tuple(pibScheme, pibLocation);
544 KeyChain::createPib(
const std::string& pibLocator)
546 std::string pibScheme, pibLocation;
547 std::tie(pibScheme, pibLocation) = parseAndCheckPibLocator(pibLocator);
548 auto pibFactory = getPibFactories().find(pibScheme);
549 BOOST_ASSERT(pibFactory != getPibFactories().end());
550 return unique_ptr<Pib>(
new Pib(pibScheme, pibLocation, pibFactory->second(pibLocation)));
553 std::tuple<std::string, std::string>
554 KeyChain::parseAndCheckTpmLocator(
const std::string& tpmLocator)
556 std::string tpmScheme, tpmLocation;
559 if (tpmScheme.empty()) {
560 tpmScheme = getDefaultTpmScheme();
562 auto tpmFactory = getTpmFactories().find(tpmScheme);
563 if (tpmFactory == getTpmFactories().end()) {
567 return std::make_tuple(tpmScheme, tpmLocation);
571 KeyChain::createTpm(
const std::string& tpmLocator)
573 std::string tpmScheme, tpmLocation;
574 std::tie(tpmScheme, tpmLocation) = parseAndCheckTpmLocator(tpmLocator);
575 auto tpmFactory = getTpmFactories().find(tpmScheme);
576 BOOST_ASSERT(tpmFactory != getTpmFactories().end());
577 return unique_ptr<Tpm>(
new Tpm(tpmScheme, tpmLocation, tpmFactory->second(tpmLocation)));
583 KeyChain::selfSign(
Key& key)
592 certificate.
setName(certificateName);
610 key.addCertificate(certificate);
614 std::tuple<Name, SignatureInfo>
615 KeyChain::prepareSignatureInfo(
const SigningInfo& params)
624 identity = m_pib->getDefaultIdentity();
664 identity = m_pib->getIdentity(identityName);
665 key = identity.
getKey(keyName);
680 if (!m_tpm->hasKey(keyName)) {
681 m_tpm->importPrivateKey(keyName, params.
getHmacKey());
686 return std::make_tuple(keyName, sigInfo);
689 NDN_THROW(InvalidSigningInfoError(
"Unrecognized signer type " +
696 NDN_THROW(InvalidSigningInfoError(
"Cannot determine signing parameters"));
703 "` does not have a default certificate"));
713 return std::make_tuple(key.
getName(), sigInfo);
719 using namespace transform;
727 auto signature = m_tpm->sign(bufs, keyName, digestAlgorithm);
729 NDN_THROW(InvalidSigningInfoError(
"TPM signing failed for key `" + keyName.
toUri() +
"` " 730 "(e.g., PIB contains info about the key, but TPM is missing " 731 "the corresponding private key)"));
748 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.
Sign Interest using Packet Specification v0.3 semantics.
Key getKey(const Name &keyName) const
Get a key with id keyName.
Data & setContentType(uint32_t type)
The certificate following the certificate format naming convention.
represents a semantic error
Buffer getPublicKey() const
Get public key bits (in PKCS#8 format)
Represents a SignatureInfo or InterestSignatureInfo 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.
Key createKey(const Identity &identity, const KeyParams ¶ms=getDefaultKeyParams())
Create a new key for identity.
Name getIdentity() const
Get identity name.
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.
SignatureInfo & setValidityPeriod(optional< security::ValidityPeriod > validityPeriod)
Append or replace ValidityPeriod.
const Key & getPibKey() const
void sign(Data &data, const SigningInfo ¶ms=SigningInfo())
Sign a Data packet according to the supplied signing information.
InputBuffers extractSignedRanges() const
Extract ranges of Interest covered by the signature in Packet Specification v0.3. ...
Represents a TLV element of the 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.
HMAC key, supports sign/verify operations.
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.
#define NDN_CXX_KEYCHAIN_REGISTER_TPM_BACKEND(TpmType)
Register Tpm backend class in KeyChain.
Interest & setSignatureValue(ConstBufferPtr value)
Set the InterestSignatureValue.
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.
Data & setSignatureInfo(const SignatureInfo &info)
Set SignatureInfo.
#define NDN_CXX_KEYCHAIN_REGISTER_PIB_BACKEND(PibType)
Register Pib backend class in KeyChain.
A frontend handle of a key instance.
No signer is specified, use default setting or follow the trust schema.
SignedInterestFormat getSignedInterestFormat() const
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.
static const SigningInfo & getDefaultSigningInfo()
Elliptic Curve key (e.g. for ECDSA), supports sign/verify operations.
const Name & getName() const noexcept
Get name.
static const Name & getDigestSha256Identity()
A localhost identity to indicate that the signature is generated using SHA-256.
Use the SHA-256 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.
SignatureInfo & setSignatureType(tlv::SignatureTypeValue type)
Set SignatureType.
Signer is a key, use its default certificate.
size_t wireEncode(EncodingImpl< TAG > &encoder, Type type=Type::Data) const
Fast encoding or block size estimation.
Interest & setSignatureInfo(const SignatureInfo &info)
Set the InterestSignatureInfo.
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)
shared_ptr< Buffer > buf()
Flush written data to the stream and return shared pointer to the underlying buffer.
System configuration file for NDN platform.
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 Block & getContent() const noexcept
Get the Content element.
SignatureInfo & setKeyLocator(optional< KeyLocator > keyLocator)
Set KeyLocator.
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.
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.
size_t wireEncode(EncodingImpl< TAG > &encoder) const
Fast encoding or block size estimation.
const KeyContainer & getKeys() const
Get all keys for this identity.
implements an output stream that constructs ndn::Buffer
#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 Parsed & getParsedConfiguration() const
const Name & getIdentity() const
Get the name of the belonging identity.
EncodingImpl< EncoderTag > EncodingBuffer
SignerType getSignerType() const
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.