60c6085c08e636d10a34ede9a6fc6f0c18fcce1f
[shibboleth/cpp-opensaml.git] / saml / saml2 / core / impl / Assertions.cpp
1 /*
2  *  Copyright 2001-2010 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 #include <xmltooling/signature/KeyInfo.h>
38 #include <xmltooling/util/ParserPool.h>
39
40 #include <xsec/utils/XSECPlatformUtils.hpp>
41
42 using namespace opensaml::saml2md;
43 using namespace opensaml::saml2;
44 using namespace xmlencryption;
45 using namespace xmlsignature;
46 using namespace xmltooling;
47 using namespace std;
48
49 void EncryptedElementType::encrypt(
50     const EncryptableObject& xmlObject,
51     const MetadataProvider& metadataProvider,
52     MetadataCredentialCriteria& criteria,
53     bool compact,
54     const XMLCh* algorithm
55     )
56 {
57     // With one recipient, we let the library generate the encryption key for us.
58     // Get the key encryption key to use.
59     criteria.setUsage(Credential::ENCRYPTION_CREDENTIAL);
60     const Credential* KEK = metadataProvider.resolve(&criteria);
61     if (!KEK)
62         throw EncryptionException("No key encryption credential found.");
63
64     // Try and find EncryptionMethod information surrounding the credential.
65     const MetadataCredentialContext* metaCtx = dynamic_cast<const MetadataCredentialContext*>(KEK->getCredentalContext());
66     if (metaCtx) {
67         const vector<EncryptionMethod*> encMethods = metaCtx->getKeyDescriptor().getEncryptionMethods();
68         if (!encMethods.empty())
69             algorithm = encMethods.front()->getAlgorithm();
70     }
71
72     if (!algorithm || !*algorithm)
73         algorithm = DSIGConstants::s_unicodeStrURIAES256_CBC;
74
75     Encrypter encrypter;
76     Encrypter::EncryptionParams ep(algorithm, NULL, 0, NULL, compact);
77     Encrypter::KeyEncryptionParams kep(*KEK);
78     setEncryptedData(encrypter.encryptElement(xmlObject.getDOM(),ep,&kep));
79 }
80
81 void EncryptedElementType::encrypt(
82     const EncryptableObject& xmlObject,
83     const vector< pair<const MetadataProvider*, MetadataCredentialCriteria*> >& recipients,
84     bool compact,
85     const XMLCh* algorithm
86     )
87 {
88     // With multiple recipients, we have to generate an encryption key and then multicast it,
89     // so we need to split the encryption and key wrapping steps.
90     if (!algorithm || !*algorithm)
91         algorithm = DSIGConstants::s_unicodeStrURIAES256_CBC;
92
93     // Generate a random key.
94     unsigned char keyBuffer[32];
95     if (XSECPlatformUtils::g_cryptoProvider->getRandom(keyBuffer,32)<32)
96         throw EncryptionException("Unable to generate encryption key; was PRNG seeded?");
97     Encrypter encrypter;
98     Encrypter::EncryptionParams ep(algorithm, keyBuffer, 32, NULL, compact);
99     setEncryptedData(encrypter.encryptElement(xmlObject.getDOM(),ep));
100     getEncryptedData()->setId(SAMLConfig::getConfig().generateIdentifier());
101
102     // Generate a uniquely named KeyInfo.
103     KeyInfo* keyInfo = KeyInfoBuilder::buildKeyInfo();
104     getEncryptedData()->setKeyInfo(keyInfo);
105     KeyName* carriedName = KeyNameBuilder::buildKeyName();
106     keyInfo->getKeyNames().push_back(carriedName);
107     carriedName->setName(SAMLConfig::getConfig().generateIdentifier());
108
109     VectorOf(EncryptedKey) keys = getEncryptedKeys();
110
111     // Now we encrypt the key for each recipient.
112     for (vector< pair<const MetadataProvider*, MetadataCredentialCriteria*> >::const_iterator r = recipients.begin(); r!=recipients.end(); ++r) {
113         // Get key encryption key to use.
114         r->second->setUsage(Credential::ENCRYPTION_CREDENTIAL);
115         const Credential* KEK = r->first->resolve(r->second);
116         if (!KEK) {
117             auto_ptr_char name(dynamic_cast<const EntityDescriptor*>(r->second->getRole().getParent())->getEntityID());
118             logging::Category::getInstance(SAML_LOGCAT".Encryption").warn("No key encryption credential found for (%s).", name.get());
119             continue;
120         }
121
122         // Encrypt the key and add it to the message.
123         Encrypter::KeyEncryptionParams kep(
124             *KEK, Encrypter::getKeyTransportAlgorithm(*KEK, algorithm),
125             dynamic_cast<const EntityDescriptor*>(r->second->getRole().getParent())->getEntityID()
126             );
127         EncryptedKey* encryptedKey = encrypter.encryptKey(keyBuffer, ep.m_keyBufferSize, kep, compact);
128         keys.push_back(encryptedKey);
129         if (keys.size()>1) {
130             // Copy details from the other key.
131             encryptedKey->setCarriedKeyName(keys.front()->getCarriedKeyName()->cloneCarriedKeyName());
132             encryptedKey->setReferenceList(keys.front()->getReferenceList()->cloneReferenceList());
133         }
134         else {
135             // Attach the carried key name.
136             CarriedKeyName* carried = CarriedKeyNameBuilder::buildCarriedKeyName();
137             carried->setName(carriedName->getName());
138             encryptedKey->setCarriedKeyName(carried);
139
140             // Attach a back-reference to the data.
141             ReferenceList* reflist = ReferenceListBuilder::buildReferenceList();
142             encryptedKey->setReferenceList(reflist);
143             DataReference* dataref = DataReferenceBuilder::buildDataReference();
144             reflist->getDataReferences().push_back(dataref);
145             XMLCh* uri = new XMLCh[XMLString::stringLen(getEncryptedData()->getId()) + 2];
146             *uri = chPound;
147             *(uri+1) = chNull;
148             XMLString::catString(uri, getEncryptedData()->getId());
149             dataref->setURI(uri);
150             delete[] uri;
151         }
152     }
153 }
154
155 XMLObject* EncryptedElementType::decrypt(const CredentialResolver& credResolver, const XMLCh* recipient, CredentialCriteria* criteria) const
156 {
157     if (!getEncryptedData())
158         throw DecryptionException("No encrypted data present.");
159     EncryptedKeyResolver ekr(*this);
160     Decrypter decrypter(&credResolver, criteria, &ekr);
161     DOMDocumentFragment* frag = decrypter.decryptData(*getEncryptedData(), recipient);
162     if (frag->hasChildNodes() && frag->getFirstChild()==frag->getLastChild()) {
163         DOMNode* plaintext=frag->getFirstChild();
164         if (plaintext->getNodeType()==DOMNode::ELEMENT_NODE) {
165             // Import the tree into a new Document that we can bind to the unmarshalled object.
166             XercesJanitor<DOMDocument> newdoc(XMLToolingConfig::getConfig().getParser().newDocument());
167             DOMElement* treecopy;
168             try {
169                 treecopy = static_cast<DOMElement*>(newdoc->importNode(plaintext, true));
170             }
171             catch (XMLException& ex) {
172                 frag->release();
173                 auto_ptr_char temp(ex.getMessage());
174                 throw DecryptionException(
175                     string("Error importing decypted DOM into new document: ") + (temp.get() ? temp.get() : "no message")
176                     );
177             }
178             frag->release();
179             newdoc->appendChild(treecopy);
180             auto_ptr<XMLObject> ret(XMLObjectBuilder::buildOneFromElement(treecopy, true));
181             newdoc.release();
182             return ret.release();
183         }
184     }
185     frag->release();
186     throw DecryptionException("Decryption did not result in a single element.");
187 }