2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
24 * Built-in behavior for SAML 2.0 Assertion interfaces.
28 #include "exceptions.h"
29 #include "saml/encryption/EncryptedKeyResolver.h"
30 #include "saml2/core/Assertions.h"
31 #include "saml2/metadata/Metadata.h"
32 #include "saml2/metadata/MetadataProvider.h"
33 #include "saml2/metadata/MetadataCredentialContext.h"
34 #include "saml2/metadata/MetadataCredentialCriteria.h"
36 #include <xmltooling/logging.h>
37 #include <xmltooling/XMLToolingConfig.h>
38 #include <xmltooling/encryption/Encrypter.h>
39 #include <xmltooling/encryption/Decrypter.h>
40 #include <xmltooling/security/Credential.h>
41 #include <xmltooling/signature/KeyInfo.h>
42 #include <xmltooling/util/ParserPool.h>
44 #include <xsec/utils/XSECPlatformUtils.hpp>
46 using namespace opensaml::saml2md;
47 using namespace opensaml::saml2;
48 using namespace xmlencryption;
49 using namespace xmlsignature;
50 using namespace xmltooling;
53 void EncryptedElementType::encrypt(
54 const EncryptableObject& xmlObject,
55 const MetadataProvider& metadataProvider,
56 MetadataCredentialCriteria& criteria,
58 const XMLCh* algorithm
61 XMLToolingConfig& conf = XMLToolingConfig::getConfig();
63 // With one recipient, we let the library generate the encryption key for us.
64 // Get the key encryption key to use. To make use of EncryptionMethod, we have
65 // to examine each possible credential in conjunction with the algorithms we
67 criteria.setUsage(Credential::ENCRYPTION_CREDENTIAL);
68 vector<const Credential*> creds;
69 if (metadataProvider.resolve(creds, &criteria) == 0)
70 throw EncryptionException("No peer encryption credential found.");
74 const Credential* KEK = nullptr;
76 for (vector<const Credential*>::const_iterator c = creds.begin(); !KEK && c != creds.end(); ++c) {
77 // Try and find EncryptionMethod information surrounding the credential.
78 // All we're doing if they're present is setting algorithms where possible to
79 // the algorithms preferred by the credential, if we support them.
80 // The problem is that if we don't support them, the only case we can detect
81 // is if neither algorithm type is set *and* there's an EncryptionMethod present.
82 dataalg = keyalg = nullptr;
83 const MetadataCredentialContext* metaCtx = dynamic_cast<const MetadataCredentialContext*>((*c)->getCredentalContext());
85 const vector<EncryptionMethod*>& encMethods = metaCtx->getKeyDescriptor().getEncryptionMethods();
86 for (vector<EncryptionMethod*>::const_iterator meth = encMethods.begin(); meth != encMethods.end(); ++meth) {
87 if ((*meth)->getAlgorithm()) {
88 if (!dataalg && conf.isXMLAlgorithmSupported((*meth)->getAlgorithm(), XMLToolingConfig::ALGTYPE_ENCRYPT))
89 dataalg = (*meth)->getAlgorithm();
90 else if (!keyalg && conf.isXMLAlgorithmSupported((*meth)->getAlgorithm(), XMLToolingConfig::ALGTYPE_KEYENCRYPT))
91 keyalg = (*meth)->getAlgorithm();
95 if (!dataalg && !keyalg && !encMethods.empty()) {
96 // We know nothing, and something was specified that we don't support, so keep looking.
101 if (!keyalg && !(keyalg = Encrypter::getKeyTransportAlgorithm(*(*c), algorithm ? algorithm : dataalg))) {
102 // We can't derive a supported algorithm from the credential, so it will fail later anyway.
111 throw EncryptionException("No supported peer encryption credential found.");
113 // Passed in algorithm takes precedence.
114 if (algorithm && *algorithm)
117 #ifdef XSEC_OPENSSL_HAVE_AES
118 dataalg = DSIGConstants::s_unicodeStrURIAES256_CBC;
120 dataalg = DSIGConstants::s_unicodeStrURI3DES_CBC;
125 Encrypter::EncryptionParams ep(dataalg, nullptr, 0, nullptr, compact);
126 Encrypter::KeyEncryptionParams kep(*KEK, keyalg);
127 setEncryptedData(encrypter.encryptElement(xmlObject.marshall(), ep, &kep));
130 void EncryptedElementType::encrypt(
131 const EncryptableObject& xmlObject,
132 const vector< pair<const MetadataProvider*, MetadataCredentialCriteria*> >& recipients,
134 const XMLCh* algorithm
137 // With multiple recipients, we have to generate an encryption key and then multicast it,
138 // so we need to split the encryption and key wrapping steps.
139 if (!algorithm || !*algorithm) {
140 #ifdef XSEC_OPENSSL_HAVE_AES
141 algorithm = DSIGConstants::s_unicodeStrURIAES256_CBC;
143 algorithm = DSIGConstants::s_unicodeStrURI3DES_CBC;
147 // Generate a random key.
148 unsigned char keyBuffer[32];
149 if (XSECPlatformUtils::g_cryptoProvider->getRandom(keyBuffer,32)<32)
150 throw EncryptionException("Unable to generate encryption key; was PRNG seeded?");
152 Encrypter::EncryptionParams ep(algorithm, keyBuffer, 32, nullptr, compact);
153 setEncryptedData(encrypter.encryptElement(xmlObject.marshall(), ep));
154 getEncryptedData()->setId(SAMLConfig::getConfig().generateIdentifier());
156 // Generate a uniquely named KeyInfo.
157 KeyInfo* keyInfo = KeyInfoBuilder::buildKeyInfo();
158 getEncryptedData()->setKeyInfo(keyInfo);
159 KeyName* carriedName = KeyNameBuilder::buildKeyName();
160 keyInfo->getKeyNames().push_back(carriedName);
161 carriedName->setName(SAMLConfig::getConfig().generateIdentifier());
163 VectorOf(EncryptedKey) keys = getEncryptedKeys();
165 // Now we encrypt the key for each recipient.
166 for (vector< pair<const MetadataProvider*, MetadataCredentialCriteria*> >::const_iterator r = recipients.begin(); r!=recipients.end(); ++r) {
167 // Get key encryption keys to use.
168 r->second->setUsage(Credential::ENCRYPTION_CREDENTIAL);
169 vector<const Credential*> creds;
170 if (r->first->resolve(creds, r->second) == 0) {
171 auto_ptr_char name(dynamic_cast<const EntityDescriptor*>(r->second->getRole().getParent())->getEntityID());
172 logging::Category::getInstance(SAML_LOGCAT".Encryption").warn("No key encryption credentials found for (%s).", name.get());
177 const Credential* KEK = nullptr;
179 for (vector<const Credential*>::const_iterator c = creds.begin(); !KEK && c != creds.end(); ++c) {
180 // Try and find EncryptionMethod information surrounding the credential.
181 // All we're doing if they're present is setting algorithms where possible to
182 // the algorithms preferred by the credential, if we support them.
183 // The problem is that if we don't support them, the only case we can detect
184 // is if neither algorithm type is set *and* there's an EncryptionMethod present.
186 const MetadataCredentialContext* metaCtx = dynamic_cast<const MetadataCredentialContext*>((*c)->getCredentalContext());
188 const vector<EncryptionMethod*>& encMethods = metaCtx->getKeyDescriptor().getEncryptionMethods();
189 for (vector<EncryptionMethod*>::const_iterator meth = encMethods.begin(); meth != encMethods.end(); ++meth) {
190 if ((*meth)->getAlgorithm()) {
191 if (!keyalg && XMLToolingConfig::getConfig().isXMLAlgorithmSupported((*meth)->getAlgorithm(), XMLToolingConfig::ALGTYPE_KEYENCRYPT))
192 keyalg = (*meth)->getAlgorithm();
197 if (!keyalg && !(keyalg = Encrypter::getKeyTransportAlgorithm(*(*c), algorithm))) {
198 // We can't derive a supported algorithm from the credential, so it will fail later anyway.
207 auto_ptr_char name(dynamic_cast<const EntityDescriptor*>(r->second->getRole().getParent())->getEntityID());
208 logging::Category::getInstance(SAML_LOGCAT".Encryption").warn("no supported key encryption credential found for (%s).", name.get());
212 // Encrypt the key and add it to the message.
213 Encrypter::KeyEncryptionParams kep(
214 *KEK, keyalg, dynamic_cast<const EntityDescriptor*>(r->second->getRole().getParent())->getEntityID()
216 EncryptedKey* encryptedKey = encrypter.encryptKey(keyBuffer, ep.m_keyBufferSize, kep, compact);
217 keys.push_back(encryptedKey);
218 if (keys.size() > 1) {
219 // Copy details from the other key.
220 encryptedKey->setCarriedKeyName(keys.front()->getCarriedKeyName()->cloneCarriedKeyName());
221 encryptedKey->setReferenceList(keys.front()->getReferenceList()->cloneReferenceList());
224 // Attach the carried key name.
225 CarriedKeyName* carried = CarriedKeyNameBuilder::buildCarriedKeyName();
226 carried->setName(carriedName->getName());
227 encryptedKey->setCarriedKeyName(carried);
229 // Attach a back-reference to the data.
230 ReferenceList* reflist = ReferenceListBuilder::buildReferenceList();
231 encryptedKey->setReferenceList(reflist);
232 DataReference* dataref = DataReferenceBuilder::buildDataReference();
233 reflist->getDataReferences().push_back(dataref);
234 XMLCh* uri = new XMLCh[XMLString::stringLen(getEncryptedData()->getId()) + 2];
237 XMLString::catString(uri, getEncryptedData()->getId());
238 dataref->setURI(uri);
244 XMLObject* EncryptedElementType::decrypt(const CredentialResolver& credResolver, const XMLCh* recipient, CredentialCriteria* criteria) const
246 if (!getEncryptedData())
247 throw DecryptionException("No encrypted data present.");
248 opensaml::EncryptedKeyResolver ekr(*this);
249 Decrypter decrypter(&credResolver, criteria, &ekr);
250 DOMDocumentFragment* frag = decrypter.decryptData(*getEncryptedData(), recipient);
251 if (frag->hasChildNodes() && frag->getFirstChild()==frag->getLastChild()) {
252 DOMNode* plaintext=frag->getFirstChild();
253 if (plaintext->getNodeType()==DOMNode::ELEMENT_NODE) {
254 // Import the tree into a new Document that we can bind to the unmarshalled object.
255 XercesJanitor<DOMDocument> newdoc(XMLToolingConfig::getConfig().getParser().newDocument());
256 DOMElement* treecopy;
258 treecopy = static_cast<DOMElement*>(newdoc->importNode(plaintext, true));
260 catch (XMLException& ex) {
262 auto_ptr_char temp(ex.getMessage());
263 throw DecryptionException(
264 string("Error importing decypted DOM into new document: ") + (temp.get() ? temp.get() : "no message")
268 newdoc->appendChild(treecopy);
269 auto_ptr<XMLObject> ret(XMLObjectBuilder::buildOneFromElement(treecopy, true));
271 return ret.release();
275 throw DecryptionException("Decryption did not result in a single element.");