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