6dbd6c8b71c04c5429d1b3c35dd3a4c193e26bd7
[shibboleth/cpp-opensaml.git] / saml / saml2 / core / impl / Assertions.cpp
1 /*
2  *  Copyright 2001-2009 Internet2
3  * 
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * Assertions.cpp
19  * 
20  * Built-in behavior for SAML 2.0 Assertion interfaces.
21  */
22
23 #include "internal.h"
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"
31
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
38 #include <xsec/utils/XSECPlatformUtils.hpp>
39
40 using namespace opensaml::saml2md;
41 using namespace opensaml::saml2;
42 using namespace xmlencryption;
43 using namespace xmlsignature;
44 using namespace xmltooling;
45 using namespace std;
46
47 void EncryptedElementType::encrypt(
48     const EncryptableObject& xmlObject,
49     const MetadataProvider& metadataProvider,
50     MetadataCredentialCriteria& criteria,
51     bool compact,
52     const XMLCh* algorithm
53     )
54 {
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);
59     if (!KEK)
60         throw EncryptionException("No key encryption credential found.");
61
62     // Try and find EncryptionMethod information surrounding the credential.
63     const MetadataCredentialContext* metaCtx = dynamic_cast<const MetadataCredentialContext*>(KEK->getCredentalContext());
64     if (metaCtx) {
65         const vector<EncryptionMethod*> encMethods = metaCtx->getKeyDescriptor().getEncryptionMethods();
66         if (!encMethods.empty())
67             algorithm = encMethods.front()->getAlgorithm();
68     }
69
70     if (!algorithm || !*algorithm)
71         algorithm = DSIGConstants::s_unicodeStrURIAES256_CBC;
72
73     Encrypter encrypter;
74     Encrypter::EncryptionParams ep(algorithm, NULL, 0, NULL, compact);
75     Encrypter::KeyEncryptionParams kep(*KEK);
76     setEncryptedData(encrypter.encryptElement(xmlObject.getDOM(),ep,&kep));
77 }
78
79 void EncryptedElementType::encrypt(
80     const EncryptableObject& xmlObject,
81     const vector< pair<const MetadataProvider*, MetadataCredentialCriteria*> >& recipients,
82     bool compact,
83     const XMLCh* algorithm
84     )
85 {
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;
90
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?");
95     Encrypter encrypter;
96     Encrypter::EncryptionParams ep(algorithm, keyBuffer, 32, NULL, compact);
97     setEncryptedData(encrypter.encryptElement(xmlObject.getDOM(),ep));
98     getEncryptedData()->setId(SAMLConfig::getConfig().generateIdentifier());
99
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());
106
107     VectorOf(EncryptedKey) keys = getEncryptedKeys();
108
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);
114         if (!KEK) {
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());
117             continue;
118         }
119
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()
124             );
125         EncryptedKey* encryptedKey = encrypter.encryptKey(keyBuffer, ep.m_keyBufferSize, kep, compact);
126         keys.push_back(encryptedKey);
127         if (keys.size()>1) {
128             // Copy details from the other key.
129             encryptedKey->setCarriedKeyName(keys.front()->getCarriedKeyName()->cloneCarriedKeyName());
130             encryptedKey->setReferenceList(keys.front()->getReferenceList()->cloneReferenceList());
131         }
132         else {
133             // Attach the carried key name.
134             CarriedKeyName* carried = CarriedKeyNameBuilder::buildCarriedKeyName();
135             carried->setName(carriedName->getName());
136             encryptedKey->setCarriedKeyName(carried);
137
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];
144             *uri = chPound;
145             *(uri+1) = chNull;
146             XMLString::catString(uri, getEncryptedData()->getId());
147             dataref->setURI(uri);
148             delete[] uri;
149         }
150     }
151 }
152
153 XMLObject* EncryptedElementType::decrypt(const CredentialResolver& credResolver, const XMLCh* recipient, CredentialCriteria* criteria) const
154 {
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));
168             newdoc.release();
169             return ret.release();
170         }
171     }
172     frag->release();
173     throw DecryptionException("Decryption did not result in a single element.");
174 }