2 * Copyright 2001-2007 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/encryption/Encrypter.h>
34 #include <xmltooling/encryption/Decrypter.h>
36 using namespace opensaml::saml2md;
37 using namespace opensaml::saml2;
38 using namespace xmlencryption;
39 using namespace xmlsignature;
40 using namespace xmltooling;
43 void EncryptedElementType::encrypt(
44 const EncryptableObject& xmlObject,
45 const MetadataProvider& metadataProvider,
46 MetadataCredentialCriteria& criteria,
48 const XMLCh* algorithm
51 // With one recipient, we let the library generate the encryption key for us.
52 // Get the key encryption key to use.
53 criteria.setUsage(Credential::ENCRYPTION_CREDENTIAL);
54 const Credential* KEK = metadataProvider.resolve(&criteria);
56 throw EncryptionException("No key encryption credential found.");
58 // Try and find EncryptionMethod information surrounding the credential.
59 const MetadataCredentialContext* metaCtx = dynamic_cast<const MetadataCredentialContext*>(KEK->getCredentalContext());
61 const vector<EncryptionMethod*> encMethods = metaCtx->getKeyDescriptor().getEncryptionMethods();
62 if (!encMethods.empty())
63 algorithm = encMethods.front()->getAlgorithm();
66 if (!algorithm || !*algorithm)
67 algorithm = DSIGConstants::s_unicodeStrURIAES256_CBC;
70 Encrypter::EncryptionParams ep(algorithm, NULL, 0, NULL, compact);
71 Encrypter::KeyEncryptionParams kep(*KEK);
72 setEncryptedData(encrypter.encryptElement(xmlObject.getDOM(),ep,&kep));
75 void EncryptedElementType::encrypt(
76 const EncryptableObject& xmlObject,
77 const vector< pair<const MetadataProvider*, MetadataCredentialCriteria*> >& recipients,
79 const XMLCh* algorithm
82 // With multiple recipients, we have to generate an encryption key and then multicast it,
83 // so we need to split the encryption and key wrapping steps.
84 if (!algorithm || !*algorithm)
85 algorithm = DSIGConstants::s_unicodeStrURIAES256_CBC;
87 // Generate a random key.
88 unsigned char keyBuffer[32];
89 if (XSECPlatformUtils::g_cryptoProvider->getRandom(keyBuffer,32)<32)
90 throw EncryptionException("Unable to generate encryption key; was PRNG seeded?");
92 Encrypter::EncryptionParams ep(algorithm, keyBuffer, 32, NULL, compact);
93 setEncryptedData(encrypter.encryptElement(xmlObject.getDOM(),ep));
94 getEncryptedData()->setId(SAMLConfig::getConfig().generateIdentifier());
96 // Generate a uniquely named KeyInfo.
97 KeyInfo* keyInfo = KeyInfoBuilder::buildKeyInfo();
98 getEncryptedData()->setKeyInfo(keyInfo);
99 KeyName* carriedName = KeyNameBuilder::buildKeyName();
100 keyInfo->getKeyNames().push_back(carriedName);
101 carriedName->setName(SAMLConfig::getConfig().generateIdentifier());
103 VectorOf(EncryptedKey) keys = getEncryptedKeys();
105 // Now we encrypt the key for each recipient.
106 for (vector< pair<const MetadataProvider*, MetadataCredentialCriteria*> >::const_iterator r = recipients.begin(); r!=recipients.end(); ++r) {
107 // Get key encryption key to use.
108 r->second->setUsage(Credential::ENCRYPTION_CREDENTIAL);
109 const Credential* KEK = r->first->resolve(r->second);
111 auto_ptr_char name(dynamic_cast<const EntityDescriptor*>(r->second->getRole().getParent())->getEntityID());
112 logging::Category::getInstance(SAML_LOGCAT".Encryption").warn("No key encryption credential found for (%s).", name.get());
116 // Encrypt the key and add it to the message.
117 Encrypter::KeyEncryptionParams kep(
118 *KEK, Encrypter::getKeyTransportAlgorithm(*KEK, algorithm),
119 dynamic_cast<const EntityDescriptor*>(r->second->getRole().getParent())->getEntityID()
121 EncryptedKey* encryptedKey = encrypter.encryptKey(keyBuffer, ep.m_keyBufferSize, kep, compact);
122 keys.push_back(encryptedKey);
124 // Copy details from the other key.
125 encryptedKey->setCarriedKeyName(keys.front()->getCarriedKeyName()->cloneCarriedKeyName());
126 encryptedKey->setReferenceList(keys.front()->getReferenceList()->cloneReferenceList());
129 // Attach the carried key name.
130 CarriedKeyName* carried = CarriedKeyNameBuilder::buildCarriedKeyName();
131 carried->setName(carriedName->getName());
132 encryptedKey->setCarriedKeyName(carried);
134 // Attach a back-reference to the data.
135 ReferenceList* reflist = ReferenceListBuilder::buildReferenceList();
136 encryptedKey->setReferenceList(reflist);
137 DataReference* dataref = DataReferenceBuilder::buildDataReference();
138 reflist->getDataReferences().push_back(dataref);
139 XMLCh* uri = new XMLCh[XMLString::stringLen(getEncryptedData()->getId()) + 2];
142 XMLString::catString(uri, getEncryptedData()->getId());
143 dataref->setURI(uri);
149 XMLObject* EncryptedElementType::decrypt(const CredentialResolver& credResolver, const XMLCh* recipient, CredentialCriteria* criteria) const
151 if (!getEncryptedData())
152 throw DecryptionException("No encrypted data present.");
153 EncryptedKeyResolver ekr(*this);
154 Decrypter decrypter(&credResolver, criteria, &ekr);
155 DOMDocumentFragment* frag = decrypter.decryptData(*getEncryptedData(), recipient);
156 if (frag->hasChildNodes() && frag->getFirstChild()==frag->getLastChild()) {
157 DOMNode* plaintext=frag->getFirstChild();
158 if (plaintext->getNodeType()==DOMNode::ELEMENT_NODE) {
159 // Import the tree into a new Document that we can bind to the unmarshalled object.
160 XercesJanitor<DOMDocument> newdoc(XMLToolingConfig::getConfig().getParser().newDocument());
161 DOMElement* treecopy = static_cast<DOMElement*>(newdoc->importNode(plaintext, true));
162 newdoc->appendChild(treecopy);
163 auto_ptr<XMLObject> ret(XMLObjectBuilder::buildOneFromElement(treecopy, true));
165 return ret.release();
169 throw DecryptionException("Decryption did not result in a single element.");