2 * Copyright 2001-2010 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
20 * Built-in behavior for SAML 2.0 Assertion interfaces.
24 #include "exceptions.h"
25 #include "saml/encryption/EncryptedKeyResolver.h"
26 #include "saml2/core/Assertions.h"
27 #include "saml2/metadata/Metadata.h"
28 #include "saml2/metadata/MetadataProvider.h"
29 #include "saml2/metadata/MetadataCredentialContext.h"
30 #include "saml2/metadata/MetadataCredentialCriteria.h"
32 #include <xmltooling/logging.h>
33 #include <xmltooling/XMLToolingConfig.h>
34 #include <xmltooling/encryption/Encrypter.h>
35 #include <xmltooling/encryption/Decrypter.h>
36 #include <xmltooling/security/Credential.h>
37 #include <xmltooling/signature/KeyInfo.h>
38 #include <xmltooling/util/ParserPool.h>
40 #include <xsec/utils/XSECPlatformUtils.hpp>
42 using namespace opensaml::saml2md;
43 using namespace opensaml::saml2;
44 using namespace xmlencryption;
45 using namespace xmlsignature;
46 using namespace xmltooling;
49 void EncryptedElementType::encrypt(
50 const EncryptableObject& xmlObject,
51 const MetadataProvider& metadataProvider,
52 MetadataCredentialCriteria& criteria,
54 const XMLCh* algorithm
57 // With one recipient, we let the library generate the encryption key for us.
58 // Get the key encryption key to use.
59 criteria.setUsage(Credential::ENCRYPTION_CREDENTIAL);
60 const Credential* KEK = metadataProvider.resolve(&criteria);
62 throw EncryptionException("No key encryption credential found.");
64 // Try and find EncryptionMethod information surrounding the credential.
65 const MetadataCredentialContext* metaCtx = dynamic_cast<const MetadataCredentialContext*>(KEK->getCredentalContext());
67 const vector<EncryptionMethod*> encMethods = metaCtx->getKeyDescriptor().getEncryptionMethods();
68 if (!encMethods.empty())
69 algorithm = encMethods.front()->getAlgorithm();
72 if (!algorithm || !*algorithm)
73 algorithm = DSIGConstants::s_unicodeStrURIAES256_CBC;
76 Encrypter::EncryptionParams ep(algorithm, nullptr, 0, nullptr, compact);
77 Encrypter::KeyEncryptionParams kep(*KEK);
78 setEncryptedData(encrypter.encryptElement(xmlObject.getDOM(),ep,&kep));
81 void EncryptedElementType::encrypt(
82 const EncryptableObject& xmlObject,
83 const vector< pair<const MetadataProvider*, MetadataCredentialCriteria*> >& recipients,
85 const XMLCh* algorithm
88 // With multiple recipients, we have to generate an encryption key and then multicast it,
89 // so we need to split the encryption and key wrapping steps.
90 if (!algorithm || !*algorithm)
91 algorithm = DSIGConstants::s_unicodeStrURIAES256_CBC;
93 // Generate a random key.
94 unsigned char keyBuffer[32];
95 if (XSECPlatformUtils::g_cryptoProvider->getRandom(keyBuffer,32)<32)
96 throw EncryptionException("Unable to generate encryption key; was PRNG seeded?");
98 Encrypter::EncryptionParams ep(algorithm, keyBuffer, 32, nullptr, compact);
99 setEncryptedData(encrypter.encryptElement(xmlObject.getDOM(),ep));
100 getEncryptedData()->setId(SAMLConfig::getConfig().generateIdentifier());
102 // Generate a uniquely named KeyInfo.
103 KeyInfo* keyInfo = KeyInfoBuilder::buildKeyInfo();
104 getEncryptedData()->setKeyInfo(keyInfo);
105 KeyName* carriedName = KeyNameBuilder::buildKeyName();
106 keyInfo->getKeyNames().push_back(carriedName);
107 carriedName->setName(SAMLConfig::getConfig().generateIdentifier());
109 VectorOf(EncryptedKey) keys = getEncryptedKeys();
111 // Now we encrypt the key for each recipient.
112 for (vector< pair<const MetadataProvider*, MetadataCredentialCriteria*> >::const_iterator r = recipients.begin(); r!=recipients.end(); ++r) {
113 // Get key encryption key to use.
114 r->second->setUsage(Credential::ENCRYPTION_CREDENTIAL);
115 const Credential* KEK = r->first->resolve(r->second);
117 auto_ptr_char name(dynamic_cast<const EntityDescriptor*>(r->second->getRole().getParent())->getEntityID());
118 logging::Category::getInstance(SAML_LOGCAT".Encryption").warn("No key encryption credential found for (%s).", name.get());
122 // Encrypt the key and add it to the message.
123 Encrypter::KeyEncryptionParams kep(
124 *KEK, Encrypter::getKeyTransportAlgorithm(*KEK, algorithm),
125 dynamic_cast<const EntityDescriptor*>(r->second->getRole().getParent())->getEntityID()
127 EncryptedKey* encryptedKey = encrypter.encryptKey(keyBuffer, ep.m_keyBufferSize, kep, compact);
128 keys.push_back(encryptedKey);
130 // Copy details from the other key.
131 encryptedKey->setCarriedKeyName(keys.front()->getCarriedKeyName()->cloneCarriedKeyName());
132 encryptedKey->setReferenceList(keys.front()->getReferenceList()->cloneReferenceList());
135 // Attach the carried key name.
136 CarriedKeyName* carried = CarriedKeyNameBuilder::buildCarriedKeyName();
137 carried->setName(carriedName->getName());
138 encryptedKey->setCarriedKeyName(carried);
140 // Attach a back-reference to the data.
141 ReferenceList* reflist = ReferenceListBuilder::buildReferenceList();
142 encryptedKey->setReferenceList(reflist);
143 DataReference* dataref = DataReferenceBuilder::buildDataReference();
144 reflist->getDataReferences().push_back(dataref);
145 XMLCh* uri = new XMLCh[XMLString::stringLen(getEncryptedData()->getId()) + 2];
148 XMLString::catString(uri, getEncryptedData()->getId());
149 dataref->setURI(uri);
155 XMLObject* EncryptedElementType::decrypt(const CredentialResolver& credResolver, const XMLCh* recipient, CredentialCriteria* criteria) const
157 if (!getEncryptedData())
158 throw DecryptionException("No encrypted data present.");
159 EncryptedKeyResolver ekr(*this);
160 Decrypter decrypter(&credResolver, criteria, &ekr);
161 DOMDocumentFragment* frag = decrypter.decryptData(*getEncryptedData(), recipient);
162 if (frag->hasChildNodes() && frag->getFirstChild()==frag->getLastChild()) {
163 DOMNode* plaintext=frag->getFirstChild();
164 if (plaintext->getNodeType()==DOMNode::ELEMENT_NODE) {
165 // Import the tree into a new Document that we can bind to the unmarshalled object.
166 XercesJanitor<DOMDocument> newdoc(XMLToolingConfig::getConfig().getParser().newDocument());
167 DOMElement* treecopy;
169 treecopy = static_cast<DOMElement*>(newdoc->importNode(plaintext, true));
171 catch (XMLException& ex) {
173 auto_ptr_char temp(ex.getMessage());
174 throw DecryptionException(
175 string("Error importing decypted DOM into new document: ") + (temp.get() ? temp.get() : "no message")
179 newdoc->appendChild(treecopy);
180 auto_ptr<XMLObject> ret(XMLObjectBuilder::buildOneFromElement(treecopy, true));
182 return ret.release();
186 throw DecryptionException("Decryption did not result in a single element.");