26 #include "../util/random.hpp" 27 #include "../util/config-file.hpp" 31 #ifdef NDN_CXX_HAVE_OSX_SECURITY 33 #endif // NDN_CXX_HAVE_OSX_SECURITY 52 #if defined(NDN_CXX_HAVE_OSX_SECURITY) and defined(NDN_CXX_WITH_OSX_KEYCHAIN) 55 const std::string DEFAULT_TPM_SCHEME =
"tpm-file";
56 #endif // defined(NDN_CXX_HAVE_OSX_SECURITY) and defined(NDN_CXX_WITH_OSX_KEYCHAIN) 65 #ifdef NDN_CXX_HAVE_OSX_SECURITY 67 #endif // NDN_CXX_HAVE_OSX_SECURITY 75 : canonicalName(canonicalName)
86 static std::map<std::string, PibFactory>&
89 static std::map<std::string, PibFactory> pibFactories;
93 static std::map<std::string, TpmFactory>&
96 static std::map<std::string, TpmFactory> tpmFactories;
102 std::initializer_list<std::string> aliases,
105 for (
const std::string& alias : aliases) {
111 KeyChain::registerTpmImpl(
const std::string& canonicalName,
112 std::initializer_list<std::string> aliases,
115 for (
const std::string& alias : aliases) {
128 std::string pibLocator = parsed.get<std::string>(
"pib",
"");
129 std::string tpmLocator = parsed.get<std::string>(
"tpm",
"");
131 initialize(pibLocator, tpmLocator,
false);
135 const std::string& tpmName,
141 initialize(pibName, tpmName, allowReset);
148 static inline std::tuple<std::string, std::string>
151 size_t pos = uri.find(
':');
152 if (pos != std::string::npos) {
153 return std::make_tuple(uri.substr(0, pos),
154 uri.substr(pos + 1));
157 return std::make_tuple(uri,
"");
164 std::string defaultPibLocator = DEFAULT_PIB_SCHEME +
":";
165 return defaultPibLocator;
168 static inline std::tuple<std::string, std::string>
171 std::string pibScheme, pibLocation;
172 std::tie(pibScheme, pibLocation) =
parseUri(pibLocator);
174 if (pibScheme.empty()) {
180 BOOST_THROW_EXCEPTION(
KeyChain::Error(
"PIB scheme '" + pibScheme +
"' is not supported"));
182 pibScheme = pibFactory->second.canonicalName;
184 return std::make_tuple(pibScheme, pibLocation);
187 unique_ptr<SecPublicInfo>
192 std::string pibScheme, pibLocation;
196 return pibFactory->second.create(pibLocation);
202 std::string defaultTpmLocator = DEFAULT_TPM_SCHEME +
":";
203 return defaultTpmLocator;
206 static inline std::tuple<std::string, std::string>
209 std::string tpmScheme, tpmLocation;
210 std::tie(tpmScheme, tpmLocation) =
parseUri(tpmLocator);
212 if (tpmScheme.empty()) {
217 BOOST_THROW_EXCEPTION(
KeyChain::Error(
"TPM scheme '" + tpmScheme +
"' is not supported"));
219 tpmScheme = tpmFactory->second.canonicalName;
221 return std::make_tuple(tpmScheme, tpmLocation);
229 std::string tpmScheme, tpmLocation;
233 return tpmFactory->second.create(tpmLocation);
237 KeyChain::initialize(
const std::string& pibLocator,
238 const std::string& tpmLocator,
242 std::string pibScheme, pibLocation;
244 std::string canonicalPibLocator = pibScheme +
":" + pibLocation;
250 std::string tpmScheme, tpmLocation;
252 std::string canonicalTpmLocator = tpmScheme +
":" + tpmLocation;
257 !m_pib->getTpmLocator().empty() && m_pib->getTpmLocator() != canonicalTpmLocator)
259 BOOST_THROW_EXCEPTION(
MismatchError(
"TPM locator supplied does not match TPM locator in PIB: " 260 + m_pib->getTpmLocator() +
" != " + canonicalTpmLocator));
270 m_pib->setTpmLocator(canonicalTpmLocator);
276 m_pib->addIdentity(identityName);
281 keyName = m_pib->getDefaultKeyNameForIdentity(identityName);
283 shared_ptr<PublicKey> key = m_pib->getPublicKey(keyName);
287 keyName = generateKeyPair(identityName,
true, params);
288 m_pib->setDefaultKeyNameForIdentity(keyName);
293 keyName = generateKeyPair(identityName,
true, params);
294 m_pib->setDefaultKeyNameForIdentity(keyName);
300 certName = m_pib->getDefaultCertificateNameForKey(keyName);
304 shared_ptr<IdentityCertificate> selfCert =
selfSign(keyName);
305 m_pib->addCertificateAsIdentityDefault(*selfCert);
306 certName = selfCert->getName();
316 return generateKeyPair(identityName, isKsk, params);
323 return generateKeyPair(identityName, isKsk, params);
331 Name keyName = generateKeyPair(identityName, isKsk, params);
333 m_pib->setDefaultKeyNameForIdentity(keyName);
343 Name keyName = generateKeyPair(identityName, isKsk, params);
345 m_pib->setDefaultKeyNameForIdentity(keyName);
351 shared_ptr<IdentityCertificate>
353 const Name& signingIdentity,
356 const std::vector<CertificateSubjectDescription>& subjectDescription,
357 const Name& certPrefix)
359 shared_ptr<PublicKey> publicKey;
362 publicKey = m_pib->getPublicKey(keyName);
366 return shared_ptr<IdentityCertificate>();
371 subjectDescription, certPrefix);
374 shared_ptr<IdentityCertificate>
377 const Name& signingIdentity,
380 const std::vector<CertificateSubjectDescription>& subjectDescription,
381 const Name& certPrefix)
383 if (keyName.
size() < 1)
384 return shared_ptr<IdentityCertificate>();
386 std::string keyIdPrefix = keyName.
get(-1).
toUri().substr(0, 4);
387 if (keyIdPrefix !=
"ksk-" && keyIdPrefix !=
"dsk-")
388 return shared_ptr<IdentityCertificate>();
390 shared_ptr<IdentityCertificate> certificate = make_shared<IdentityCertificate>();
397 certName.
append(signingIdentity)
412 if (certPrefix.
isPrefixOf(keyName) && certPrefix != keyName)
413 certName.
append(certPrefix)
419 return shared_ptr<IdentityCertificate>();
423 certificate->setName(certName);
424 certificate->setNotBefore(notBefore);
425 certificate->setNotAfter(notAfter);
426 certificate->setPublicKeyInfo(publicKey);
428 if (subjectDescription.empty())
431 certificate->addSubjectDescription(subjectName);
435 std::vector<CertificateSubjectDescription>::const_iterator sdIt =
436 subjectDescription.begin();
437 std::vector<CertificateSubjectDescription>::const_iterator sdEnd =
438 subjectDescription.end();
439 for(; sdIt != sdEnd; sdIt++)
440 certificate->addSubjectDescription(*sdIt);
443 certificate->encode();
448 std::tuple<Name, SignatureInfo>
449 KeyChain::prepareSignatureInfo(
const SigningInfo& params)
453 shared_ptr<IdentityCertificate> signingCert;
458 if (m_pib->getDefaultCertificate() ==
nullptr)
459 setDefaultCertificateInternal();
461 signingCert = m_pib->getDefaultCertificate();
466 Name signingCertName;
468 signingCertName = m_pib->getDefaultCertificateNameForIdentity(params.
getSignerName());
474 signingCert = m_pib->getCertificate(signingCertName);
480 Name signingCertName;
482 signingCertName = m_pib->getDefaultCertificateNameForKey(params.
getSignerName());
485 BOOST_THROW_EXCEPTION(
Error(
"signing certificate does not exist"));
488 signingCert = m_pib->getCertificate(signingCertName);
495 if (signingCert ==
nullptr)
496 BOOST_THROW_EXCEPTION(
Error(
"signing certificate does not exist"));
506 BOOST_THROW_EXCEPTION(
Error(
"Unrecognized signer type"));
513 return std::make_tuple(signingCert->getPublicKeyName(), sigInfo);
519 signImpl(data, params);
525 signImpl(interest, params);
533 std::tie(keyName, sigInfo) = prepareSignatureInfo(params);
540 shared_ptr<IdentityCertificate> certificate = m_pib->getCertificate(certificateName);
542 if (certificate ==
nullptr)
548 sig.
setValue(m_tpm->signInTpm(buffer, bufferLength,
549 certificate->getPublicKeyName(),
555 shared_ptr<IdentityCertificate>
558 shared_ptr<PublicKey> pubKey;
560 pubKey = m_pib->getPublicKey(keyName);
563 return shared_ptr<IdentityCertificate>();
566 auto certificate = make_shared<IdentityCertificate>();
571 certificate->setName(certificateName);
574 certificate->setPublicKeyInfo(*pubKey);
577 certificate->encode();
590 BOOST_THROW_EXCEPTION(
SecTpm::Error(
"Private key does not exist"));
600 shared_ptr<SecuredBag>
603 if (!m_pib->doesIdentityExist(identity))
606 Name keyName = m_pib->getDefaultKeyNameForIdentity(identity);
611 pkcs5 = m_tpm->exportPrivateKeyPkcs5FromTpm(keyName, passwordStr);
618 shared_ptr<IdentityCertificate> cert;
621 cert = m_pib->getCertificate(m_pib->getDefaultCertificateNameForKey(keyName));
626 m_pib->addCertificateAsIdentityDefault(*cert);
630 shared_ptr<SecuredBag> secureBag(
new SecuredBag(*cert, pkcs5));
643 m_pib->addIdentity(identity);
646 m_tpm->importPrivateKeyPkcs5IntoTpm(keyName,
647 securedBag.
getKey()->buf(),
648 securedBag.
getKey()->size(),
651 shared_ptr<PublicKey> pubKey = m_tpm->getPublicKeyFromTpm(keyName.
toUri());
653 m_pib->addKey(keyName, *pubKey);
654 m_pib->setDefaultKeyNameForIdentity(keyName);
657 m_pib->addCertificateAsIdentityDefault(securedBag.
getCertificate());
661 KeyChain::setDefaultCertificateInternal()
663 m_pib->refreshDefaultCertificate();
665 if (!static_cast<bool>(m_pib->getDefaultCertificate()))
667 Name defaultIdentity;
670 defaultIdentity = m_pib->getDefaultIdentity();
675 defaultIdentity.
append(
"tmp-identity")
676 .
append(reinterpret_cast<uint8_t*>(&random), 4);
679 m_pib->setDefaultIdentity(defaultIdentity);
680 m_pib->refreshDefaultCertificate();
685 KeyChain::generateKeyPair(
const Name& identityName,
bool isKsk,
const KeyParams& params)
687 Name keyName = m_pib->getNewKeyName(identityName, isKsk);
689 m_tpm->generateKeyPairInTpm(keyName.
toUri(), params);
691 shared_ptr<PublicKey> pubKey = m_tpm->getPublicKeyFromTpm(keyName.
toUri());
692 m_pib->addKey(keyName, *pubKey);
698 KeyChain::signPacketWrapper(
Data& data,
const Signature& signature,
706 Block sigValue = pureSign(encoder.buf(), encoder.size(), keyName, digestAlgorithm);
716 if (timestamp <= m_lastTimestamp)
718 timestamp = m_lastTimestamp + time::milliseconds(1);
733 signedName.
append(sigValue);
738 KeyChain::pureSign(
const uint8_t* buf,
size_t size,
744 return m_tpm->signInTpm(buf, size, keyName, digestAlgorithm);
750 Name signingCertificateName;
753 signingCertificateName = m_pib->getDefaultCertificateNameForIdentity(identityName);
768 signingCertificateName)));
792 if (timestamp <= m_lastTimestamp)
793 timestamp = m_lastTimestamp + time::milliseconds(1);
806 signedName.
append(sigValue);
813 m_pib->deleteCertificateInfo(certificateName);
819 m_pib->deletePublicKeyInfo(keyName);
820 m_tpm->deleteKeyPairInTpm(keyName);
826 std::vector<Name> keyNames;
827 m_pib->getAllKeyNamesOfIdentity(identity, keyNames,
true);
828 m_pib->getAllKeyNamesOfIdentity(identity, keyNames,
false);
830 m_pib->deleteIdentityInfo(identity);
832 for (
const auto& keyName : keyNames)
833 m_tpm->deleteKeyPairInTpm(keyName);
845 BOOST_THROW_EXCEPTION(
Error(
"Unsupported key types"));
Factory< KeyChain::PibCreateFunc > PibFactory
static const RsaKeyParams DEFAULT_KEY_PARAMS
static std::tuple< std::string, std::string > getCanonicalTpmLocator(const std::string &tpmLocator)
static Component fromNumber(uint64_t number)
Create a component encoded as nonNegativeInteger.
shared_ptr< IdentityCertificate > prepareUnsignedIdentityCertificate(const Name &keyName, const Name &signingIdentity, const time::system_clock::TimePoint ¬Before, const time::system_clock::TimePoint ¬After, const std::vector< CertificateSubjectDescription > &subjectDescription, const Name &certPrefix=DEFAULT_PREFIX)
prepare an unsigned identity certificate
const Name & getName() const
static std::map< std::string, PibFactory > & getPibFactories()
Copyright (c) 2011-2015 Regents of the University of California.
void setSignatureType(tlv::SignatureTypeValue type)
Set SignatureType.
function< unique_ptr< SecPublicInfo >const std::string &)> PibCreateFunc
SimplePublicKeyParams< RsaKeyParamsInfo > RsaKeyParams
RsaKeyParams carries parameters for RSA key.
Data & setSignature(const Signature &signature)
Set the signature to a copy of the given signature.
A CertificateSubjectDescription represents the SubjectDescription entry in a Certificate.
KeyType getKeyType() const
void importIdentity(const SecuredBag &securedBag, const std::string &passwordStr)
import an identity.
const std::string DEFAULT_TPM_SCHEME
static unique_ptr< SecPublicInfo > createPib(const std::string &pibLocator)
Create a PIB according to pibLocator.
const Name & getSignerName() const
ConstBufferPtr getKey() const
Represent a SHA256 digest.
void signByIdentity(T &packet, const Name &identityName)
Sign packet using the default certificate of a particular identity.
const Parsed & getParsedConfiguration() const
static Name certificateNameToPublicKeyName(const Name &certificateName)
Get the public key name from the full certificate name.
Error thrown when the supplied TPM locator to KeyChain constructor does not match the locator stored ...
size_t wireEncode(EncodingImpl< TAG > &encoder) const
Fast encoding or block size estimation.
Class representing a wire element of NDN-TLV packet format.
represents an Interest packet
const Block & getValue() const
Get SignatureValue in the wire format.
use sha256 digest, no signer needs to be specified
void sign(Data &data, const SigningInfo ¶ms=DEFAULT_SIGNING_INFO)
Sign data according to the supplied signing information.
static time_point now() noexcept
Signing parameters passed to KeyChain.
shared_ptr< SecuredBag > exportIdentity(const Name &identity, const std::string &passwordStr)
export an identity.
PublicKey & getPublicKeyInfo()
const OID ATTRIBUTE_NAME("2.5.4.41")
Factory< KeyChain::TpmCreateFunc > TpmFactory
const Name & getName() const
Get name of the Data packet.
void setKeyLocator(const KeyLocator &keyLocator)
Set KeyLocator.
std::string toUri() const
Encode this name as a URI.
uint32_t generateWord32()
Generate a cryptographically non-secure random integer from the range [0, 2^32)
size_t wireEncode(EncodingImpl< TAG > &encoder, bool wantUnsignedPortionOnly=false) const
Fast encoding or block size estimation.
Data & setSignatureValue(const Block &value)
static std::tuple< std::string, std::string > getCanonicalPibLocator(const std::string &pibLocator)
static const SigningInfo DEFAULT_SIGNING_INFO
EncodingImpl< EncoderTag > EncodingBuffer
void setValue(const Block &value)
Get SignatureValue from a block.
Interest & setName(const Name &name)
boost::property_tree::ptree Parsed
no signer is specified, use default setting or follow the trust schema
Name createIdentity(const Name &identityName, const KeyParams ¶ms=DEFAULT_KEY_PARAMS)
Create an identity by creating a pair of Key-Signing-Key (KSK) for this identity and a self-signed ce...
void toUri(std::ostream &os) const
Write *this to the output stream, escaping characters according to the NDN URI Scheme.
function< unique_ptr< SecTpm >const std::string &)> TpmCreateFunc
const SignatureInfo & getSignatureInfo() const
static std::string getDefaultTpmLocator()
Get default TPM locator.
KeyType getKeyType() const
size_t size() const
Get the number of components.
Name abstraction to represent an absolute name.
signer is a certificate, use it directly
const Name & getPublicKeyName() const
Factory(const std::string &canonicalName, const T &create)
void deleteIdentity(const Name &identity)
delete an identity.
signer is a key, use its default certificate
const Signature & getSignature() const
Name generateRsaKeyPair(const Name &identityName, bool isKsk=false, uint32_t keySize=2048)
Generate a pair of RSA keys for the specified identity.
static tlv::SignatureTypeValue getSignatureType(KeyType keyType, DigestAlgorithm digestAlgorithm)
KeyChain()
Constructor to create KeyChain with default PIB and TPM.
uint64_t generateWord64()
Generate a cryptographically non-secure random integer from range [0, 2^64)
static unique_ptr< SecTpm > createTpm(const std::string &tpmLocator)
Create a TPM according to tpmLocator.
static std::string getDefaultPibLocator()
Get default PIB locator.
const std::string DEFAULT_PIB_SCHEME
const Block & getInfo() const
Get SignatureInfo in the wire format.
void encode()
Encode subblocks into wire buffer.
milliseconds toUnixTimestamp(const system_clock::TimePoint &point)
Convert system_clock::TimePoint to UNIX timestamp.
const IdentityCertificate & getCertificate() const
static std::tuple< std::string, std::string > parseUri(const std::string &uri)
Name & append(const uint8_t *value, size_t valueLength)
Append a new component, copying from value of length valueLength.
shared_ptr< IdentityCertificate > selfSign(const Name &keyName)
Generate a self-signed certificate for a public key.
Base class of key parameters.
bool isPrefixOf(const Name &name) const
Check if the N components of this name are the same as the first N components of the given name...
signer is an identity, use its default key and default certificate
PartialName getSubName(ssize_t iStartComponent, size_t nComponents=npos) const
Extract a sub-name (PartialName) of nComponents components starting from iStartComponent.
Name generateEcdsaKeyPair(const Name &identityName, bool isKsk=false, uint32_t keySize=256)
Generate a pair of ECDSA keys for the specified identity.
PartialName getPrefix(ssize_t nComponents) const
Extract a prefix (PartialName) of the name, containing first nComponents components.
#define NDN_CXX_KEYCHAIN_REGISTER_TPM(TpmType,...)
Register SecTpm class in ndn-cxx KeyChain.
static const Name DEFAULT_PREFIX
void signWithSha256(Data &data)
Set Sha256 weak signature for data.
shared_ptr< const Buffer > ConstBufferPtr
ConstBufferPtr sha256(const uint8_t *data, size_t dataLength)
Compute the sha-256 digest of data.
Name generateEcdsaKeyPairAsDefault(const Name &identityName, bool isKsk, uint32_t keySize=256)
Generate a pair of ECDSA keys for the specified identity and set it as default key for the identity...
SimplePublicKeyParams is a template for public keys with only one parameter: size.
DigestAlgorithm getDigestAlgorithm() const
Name generateRsaKeyPairAsDefault(const Name &identityName, bool isKsk=false, uint32_t keySize=2048)
Generate a pair of RSA keys for the specified identity and set it as default key for the identity...
static const Name DIGEST_SHA256_IDENTITY
A localhost identity which indicates that signature is generated using SHA-256.
#define NDN_CXX_KEYCHAIN_REGISTER_PIB(PibType,...)
Register SecPib class in ndn-cxx KeyChain.
void deleteKey(const Name &keyName)
delete a key.
const Component & get(ssize_t i) const
Get the component at the given index.
SignerType getSignerType() const
void deleteCertificate(const Name &certificateName)
delete a certificate.
duration< boost::int_least32_t, boost::ratio< 86400 > > days
Name & appendVersion(uint64_t version)
Append version using NDN naming conventions.
static std::map< std::string, TpmFactory > & getTpmFactories()
std::string canonicalName
A Signature is storage for the signature-related information (info and value) in a Data packet...