9b5495c4d5907af36a6d6a79b5a01bcc9f25eaf6
[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/encryption/Encrypter.h>
34 #include <xmltooling/encryption/Decrypter.h>
35 #include <xmltooling/security/Credential.h>
36
37 #include <xsec/utils/XSECPlatformUtils.hpp>
38
39 using namespace opensaml::saml2md;
40 using namespace opensaml::saml2;
41 using namespace xmlencryption;
42 using namespace xmlsignature;
43 using namespace xmltooling;
44 using namespace std;
45
46 void EncryptedElementType::encrypt(
47     const EncryptableObject& xmlObject,
48     const MetadataProvider& metadataProvider,
49     MetadataCredentialCriteria& criteria,
50     bool compact,
51     const XMLCh* algorithm
52     )
53 {
54     // With one recipient, we let the library generate the encryption key for us.
55     // Get the key encryption key to use.
56     criteria.setUsage(Credential::ENCRYPTION_CREDENTIAL);
57     const Credential* KEK = metadataProvider.resolve(&criteria);
58     if (!KEK)
59         throw EncryptionException("No key encryption credential found.");
60
61     // Try and find EncryptionMethod information surrounding the credential.
62     const MetadataCredentialContext* metaCtx = dynamic_cast<const MetadataCredentialContext*>(KEK->getCredentalContext());
63     if (metaCtx) {
64         const vector<EncryptionMethod*> encMethods = metaCtx->getKeyDescriptor().getEncryptionMethods();
65         if (!encMethods.empty())
66             algorithm = encMethods.front()->getAlgorithm();
67     }
68
69     if (!algorithm || !*algorithm)
70         algorithm = DSIGConstants::s_unicodeStrURIAES256_CBC;
71
72     Encrypter encrypter;
73     Encrypter::EncryptionParams ep(algorithm, NULL, 0, NULL, compact);
74     Encrypter::KeyEncryptionParams kep(*KEK);
75     setEncryptedData(encrypter.encryptElement(xmlObject.getDOM(),ep,&kep));
76 }
77
78 void EncryptedElementType::encrypt(
79     const EncryptableObject& xmlObject,
80     const vector< pair<const MetadataProvider*, MetadataCredentialCriteria*> >& recipients,
81     bool compact,
82     const XMLCh* algorithm
83     )
84 {
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;
89
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?");
94     Encrypter encrypter;
95     Encrypter::EncryptionParams ep(algorithm, keyBuffer, 32, NULL, compact);
96     setEncryptedData(encrypter.encryptElement(xmlObject.getDOM(),ep));
97     getEncryptedData()->setId(SAMLConfig::getConfig().generateIdentifier());
98
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());
105
106     VectorOf(EncryptedKey) keys = getEncryptedKeys();
107
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(Credential::ENCRYPTION_CREDENTIAL);
112         const Credential* KEK = r->first->resolve(r->second);
113         if (!KEK) {
114             auto_ptr_char name(dynamic_cast<const EntityDescriptor*>(r->second->getRole().getParent())->getEntityID());
115             logging::Category::getInstance(SAML_LOGCAT".Encryption").warn("No key encryption credential found for (%s).", name.get());
116             continue;
117         }
118
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()
123             );
124         EncryptedKey* encryptedKey = encrypter.encryptKey(keyBuffer, ep.m_keyBufferSize, kep, compact);
125         keys.push_back(encryptedKey);
126         if (keys.size()>1) {
127             // Copy details from the other key.
128             encryptedKey->setCarriedKeyName(keys.front()->getCarriedKeyName()->cloneCarriedKeyName());
129             encryptedKey->setReferenceList(keys.front()->getReferenceList()->cloneReferenceList());
130         }
131         else {
132             // Attach the carried key name.
133             CarriedKeyName* carried = CarriedKeyNameBuilder::buildCarriedKeyName();
134             carried->setName(carriedName->getName());
135             encryptedKey->setCarriedKeyName(carried);
136
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];
143             *uri = chPound;
144             *(uri+1) = chNull;
145             XMLString::catString(uri, getEncryptedData()->getId());
146             dataref->setURI(uri);
147             delete[] uri;
148         }
149     }
150 }
151
152 XMLObject* EncryptedElementType::decrypt(const CredentialResolver& credResolver, const XMLCh* recipient, CredentialCriteria* criteria) const
153 {
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));
167             newdoc.release();
168             return ret.release();
169         }
170     }
171     frag->release();
172     throw DecryptionException("Decryption did not result in a single element.");
173 }