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