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