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 <log4cpp/Category.hh>
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(CredentialCriteria::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 if (recipients.size()==1)
83 return encrypt(xmlObject, *recipients.front().first, *recipients.front().second, compact, algorithm);
85 // With multiple recipients, we have to generate an encryption key and then multicast it,
86 // so we need to split the encryption and key wrapping steps.
87 if (!algorithm || !*algorithm)
88 algorithm = DSIGConstants::s_unicodeStrURIAES256_CBC;
90 // Generate a random key.
91 unsigned char keyBuffer[32];
92 if (XSECPlatformUtils::g_cryptoProvider->getRandom(keyBuffer,32)<32)
93 throw EncryptionException("Unable to generate encryption key; was PRNG seeded?");
95 Encrypter::EncryptionParams ep(algorithm, keyBuffer, 32, NULL, compact);
96 setEncryptedData(encrypter.encryptElement(xmlObject.getDOM(),ep));
97 getEncryptedData()->setId(SAMLConfig::getConfig().generateIdentifier());
99 // Generate a uniquely named KeyInfo.
100 KeyInfo* keyInfo = KeyInfoBuilder::buildKeyInfo();
101 getEncryptedData()->setKeyInfo(keyInfo);
102 KeyName* carriedName = KeyNameBuilder::buildKeyName();
103 keyInfo->getKeyNames().push_back(carriedName);
104 carriedName->setName(SAMLConfig::getConfig().generateIdentifier());
106 VectorOf(EncryptedKey) keys = getEncryptedKeys();
108 // Now we encrypt the key for each recipient.
109 for (vector< pair<const MetadataProvider*, MetadataCredentialCriteria*> >::const_iterator r = recipients.begin(); r!=recipients.end(); ++r) {
110 // Get key encryption key to use.
111 r->second->setUsage(CredentialCriteria::ENCRYPTION_CREDENTIAL);
112 const Credential* KEK = r->first->resolve(r->second);
114 auto_ptr_char name(dynamic_cast<const EntityDescriptor*>(r->second->getRole().getParent())->getEntityID());
115 log4cpp::Category::getInstance(SAML_LOGCAT".Encryption").warn("No key encryption credential found for (%s).", name.get());
119 // Encrypt the key and add it to the message.
120 Encrypter::KeyEncryptionParams kep(
121 *KEK, Encrypter::getKeyTransportAlgorithm(*KEK, algorithm),
122 dynamic_cast<const EntityDescriptor*>(r->second->getRole().getParent())->getEntityID()
124 EncryptedKey* encryptedKey = encrypter.encryptKey(keyBuffer, ep.m_keyBufferSize, kep, compact);
125 keys.push_back(encryptedKey);
127 // Copy details from the other key.
128 encryptedKey->setCarriedKeyName(keys.front()->getCarriedKeyName()->cloneCarriedKeyName());
129 encryptedKey->setReferenceList(keys.front()->getReferenceList()->cloneReferenceList());
132 // Attach the carried key name.
133 CarriedKeyName* carried = CarriedKeyNameBuilder::buildCarriedKeyName();
134 carried->setName(carriedName->getName());
135 encryptedKey->setCarriedKeyName(carried);
137 // Attach a back-reference to the data.
138 ReferenceList* reflist = ReferenceListBuilder::buildReferenceList();
139 encryptedKey->setReferenceList(reflist);
140 DataReference* dataref = DataReferenceBuilder::buildDataReference();
141 reflist->getDataReferences().push_back(dataref);
142 XMLCh* uri = new XMLCh[XMLString::stringLen(getEncryptedData()->getId()) + 2];
145 XMLString::catString(uri, getEncryptedData()->getId());
146 dataref->setURI(uri);
152 XMLObject* EncryptedElementType::decrypt(const CredentialResolver& credResolver, const XMLCh* recipient, CredentialCriteria* criteria) const
154 if (!getEncryptedData())
155 throw DecryptionException("No encrypted data present.");
156 EncryptedKeyResolver ekr(*this);
157 Decrypter decrypter(&credResolver, criteria, &ekr);
158 DOMDocumentFragment* frag = decrypter.decryptData(*getEncryptedData(), recipient);
159 if (frag->hasChildNodes() && frag->getFirstChild()==frag->getLastChild()) {
160 DOMNode* plaintext=frag->getFirstChild();
161 if (plaintext->getNodeType()==DOMNode::ELEMENT_NODE) {
162 // Import the tree into a new Document that we can bind to the unmarshalled object.
163 XercesJanitor<DOMDocument> newdoc(XMLToolingConfig::getConfig().getParser().newDocument());
164 DOMElement* treecopy = static_cast<DOMElement*>(newdoc->importNode(plaintext, true));
165 newdoc->appendChild(treecopy);
166 auto_ptr<XMLObject> ret(XMLObjectBuilder::buildOneFromElement(treecopy, true));
168 return ret.release();
172 throw DecryptionException("Decryption did not result in a single element.");