File: Assertions.cpp

package info (click to toggle)
opensaml 3.3.1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,480 kB
  • sloc: cpp: 27,961; sh: 4,593; xml: 1,004; makefile: 429; ansic: 18
file content (278 lines) | stat: -rw-r--r-- 12,566 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/**
 * Licensed to the University Corporation for Advanced Internet
 * Development, Inc. (UCAID) under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.
 *
 * UCAID licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the
 * License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

/**
 * Assertions.cpp
 * 
 * Built-in behavior for SAML 2.0 Assertion interfaces.
 */

#include "internal.h"
#include "exceptions.h"
#include "saml/encryption/EncryptedKeyResolver.h"
#include "saml2/core/Assertions.h"
#include "saml2/metadata/Metadata.h"
#include "saml2/metadata/MetadataProvider.h"
#include "saml2/metadata/MetadataCredentialContext.h"
#include "saml2/metadata/MetadataCredentialCriteria.h"

#include <xmltooling/logging.h>
#include <xmltooling/XMLToolingConfig.h>
#include <xmltooling/encryption/Encrypter.h>
#include <xmltooling/encryption/Decrypter.h>
#include <xmltooling/security/Credential.h>
#include <xmltooling/signature/KeyInfo.h>
#include <xmltooling/util/ParserPool.h>

#include <xsec/utils/XSECPlatformUtils.hpp>

using namespace opensaml::saml2md;
using namespace opensaml::saml2;
using namespace xmlencryption;
using namespace xmlsignature;
using namespace xmltooling;
using namespace std;

void EncryptedElementType::encrypt(
    const EncryptableObject& xmlObject,
    const MetadataProvider& metadataProvider,
    MetadataCredentialCriteria& criteria,
    bool compact,
    const XMLCh* algorithm
    )
{
    XMLToolingConfig& conf = XMLToolingConfig::getConfig();

    // With one recipient, we let the library generate the encryption key for us.
    // Get the key encryption key to use. To make use of EncryptionMethod, we have
    // to examine each possible credential in conjunction with the algorithms we
    // support.
    criteria.setUsage(Credential::ENCRYPTION_CREDENTIAL);
    vector<const Credential*> creds;
    if (metadataProvider.resolve(creds, &criteria) == 0)
        throw EncryptionException("No peer encryption credential found.");

    const XMLCh* dataalg;
    const XMLCh* keyalg;
    const Credential* KEK = nullptr;

    for (vector<const Credential*>::const_iterator c = creds.begin(); !KEK && c != creds.end(); ++c) {
        // Try and find EncryptionMethod information surrounding the credential.
        // All we're doing if they're present is setting algorithms where possible to
        // the algorithms preferred by the credential, if we support them.
        // The problem is that if we don't support them, the only case we can detect
        // is if neither algorithm type is set *and* there's an EncryptionMethod present.
        dataalg = keyalg = nullptr;
        const MetadataCredentialContext* metaCtx = dynamic_cast<const MetadataCredentialContext*>((*c)->getCredentialContext());
        if (metaCtx) {
            const vector<EncryptionMethod*>& encMethods = metaCtx->getKeyDescriptor().getEncryptionMethods();
            for (vector<EncryptionMethod*>::const_iterator meth = encMethods.begin(); meth != encMethods.end(); ++meth) {
                if ((*meth)->getAlgorithm()) {
                    if (!dataalg && conf.isXMLAlgorithmSupported((*meth)->getAlgorithm(), XMLToolingConfig::ALGTYPE_ENCRYPT))
                        dataalg = (*meth)->getAlgorithm();
                    else if (!keyalg && conf.isXMLAlgorithmSupported((*meth)->getAlgorithm(), XMLToolingConfig::ALGTYPE_KEYENCRYPT))
                        keyalg = (*meth)->getAlgorithm();
                }
            }

            if (!dataalg && !keyalg && !encMethods.empty()) {
                // We know nothing, and something was specified that we don't support, so keep looking.
                continue;
            }
        }

        if (!keyalg && !(keyalg = Encrypter::getKeyTransportAlgorithm(*(*c), algorithm ? algorithm : dataalg))) {
            // We can't derive a supported algorithm from the credential, so it will fail later anyway.
            continue;
        }

        // Use this key.
        KEK = *c;
    }

    if (!KEK)
        throw EncryptionException("No supported peer encryption credential found.");

    // Passed in algorithm takes precedence.
    if (algorithm && *algorithm)
        dataalg = algorithm;
    if (!dataalg) {
#ifdef XSEC_OPENSSL_HAVE_AES
        dataalg = DSIGConstants::s_unicodeStrURIAES256_CBC;
#else
        dataalg = DSIGConstants::s_unicodeStrURI3DES_CBC;
#endif
    }

    Encrypter encrypter;
    Encrypter::EncryptionParams ep(dataalg, nullptr, 0, nullptr, compact);
    Encrypter::KeyEncryptionParams kep(*KEK, keyalg);
    setEncryptedData(encrypter.encryptElement(xmlObject.marshall(), ep, &kep));
}

void EncryptedElementType::encrypt(
    const EncryptableObject& xmlObject,
    const vector< pair<const MetadataProvider*, MetadataCredentialCriteria*> >& recipients,
    bool compact,
    const XMLCh* algorithm
    )
{
    // With multiple recipients, we have to generate an encryption key and then multicast it,
    // so we need to split the encryption and key wrapping steps.
    if (!algorithm || !*algorithm) {
#ifdef XSEC_OPENSSL_HAVE_AES
        algorithm = DSIGConstants::s_unicodeStrURIAES256_CBC;
#else
        algorithm = DSIGConstants::s_unicodeStrURI3DES_CBC;
#endif
    }

    // Generate a random key.
    unsigned char keyBuffer[32];
    if (XSECPlatformUtils::g_cryptoProvider->getRandom(keyBuffer,32)<32)
        throw EncryptionException("Unable to generate encryption key; was PRNG seeded?");
    Encrypter encrypter;
    Encrypter::EncryptionParams ep(algorithm, keyBuffer, 32, nullptr, compact);
    setEncryptedData(encrypter.encryptElement(xmlObject.marshall(), ep));
    getEncryptedData()->setId(SAMLConfig::getConfig().generateIdentifier());

    // Generate a uniquely named KeyInfo.
    KeyInfo* keyInfo = KeyInfoBuilder::buildKeyInfo();
    getEncryptedData()->setKeyInfo(keyInfo);
    KeyName* carriedName = KeyNameBuilder::buildKeyName();
    keyInfo->getKeyNames().push_back(carriedName);
    carriedName->setName(SAMLConfig::getConfig().generateIdentifier());

    VectorOf(EncryptedKey) keys = getEncryptedKeys();

    // Now we encrypt the key for each recipient.
    for (vector< pair<const MetadataProvider*, MetadataCredentialCriteria*> >::const_iterator r = recipients.begin(); r!=recipients.end(); ++r) {
        // Get key encryption keys to use.
        r->second->setUsage(Credential::ENCRYPTION_CREDENTIAL);
        vector<const Credential*> creds;
        if (r->first->resolve(creds, r->second) == 0) {
            auto_ptr_char name(dynamic_cast<const EntityDescriptor*>(r->second->getRole().getParent())->getEntityID());
            logging::Category::getInstance(SAML_LOGCAT ".Encryption").warn("No key encryption credentials found for (%s).", name.get());
            continue;
        }

        const XMLCh* keyalg;
        const Credential* KEK = nullptr;

        for (vector<const Credential*>::const_iterator c = creds.begin(); !KEK && c != creds.end(); ++c) {
            // Try and find EncryptionMethod information surrounding the credential.
            // All we're doing if they're present is setting algorithms where possible to
            // the algorithms preferred by the credential, if we support them.
            // The problem is that if we don't support them, the only case we can detect
            // is if neither algorithm type is set *and* there's an EncryptionMethod present.
            keyalg = nullptr;
            const MetadataCredentialContext* metaCtx = dynamic_cast<const MetadataCredentialContext*>((*c)->getCredentialContext());
            if (metaCtx) {
                const vector<EncryptionMethod*>& encMethods = metaCtx->getKeyDescriptor().getEncryptionMethods();
                for (vector<EncryptionMethod*>::const_iterator meth = encMethods.begin(); meth != encMethods.end(); ++meth) {
                    if ((*meth)->getAlgorithm()) {
                        if (!keyalg && XMLToolingConfig::getConfig().isXMLAlgorithmSupported((*meth)->getAlgorithm(), XMLToolingConfig::ALGTYPE_KEYENCRYPT))
                            keyalg = (*meth)->getAlgorithm();
                    }
                }
            }

            if (!keyalg && !(keyalg = Encrypter::getKeyTransportAlgorithm(*(*c), algorithm))) {
                // We can't derive a supported algorithm from the credential, so it will fail later anyway.
                continue;
            }

            // Use this key.
            KEK = *c;
        }

        if (!KEK) {
            auto_ptr_char name(dynamic_cast<const EntityDescriptor*>(r->second->getRole().getParent())->getEntityID());
            logging::Category::getInstance(SAML_LOGCAT ".Encryption").warn("no supported key encryption credential found for (%s).", name.get());
            continue;
        }

        // Encrypt the key and add it to the message.
        Encrypter::KeyEncryptionParams kep(
            *KEK, keyalg, dynamic_cast<const EntityDescriptor*>(r->second->getRole().getParent())->getEntityID()
            );
        EncryptedKey* encryptedKey = encrypter.encryptKey(keyBuffer, ep.m_keyBufferSize, kep, compact);
        keys.push_back(encryptedKey);
        if (keys.size() > 1) {
            // Copy details from the other key.
            encryptedKey->setCarriedKeyName(keys.front()->getCarriedKeyName()->cloneCarriedKeyName());
            encryptedKey->setReferenceList(keys.front()->getReferenceList()->cloneReferenceList());
        }
        else {
            // Attach the carried key name.
            CarriedKeyName* carried = CarriedKeyNameBuilder::buildCarriedKeyName();
            carried->setName(carriedName->getName());
            encryptedKey->setCarriedKeyName(carried);

            // Attach a back-reference to the data.
            ReferenceList* reflist = ReferenceListBuilder::buildReferenceList();
            encryptedKey->setReferenceList(reflist);
            DataReference* dataref = DataReferenceBuilder::buildDataReference();
            reflist->getDataReferences().push_back(dataref);
            XMLCh* uri = new XMLCh[XMLString::stringLen(getEncryptedData()->getId()) + 2];
            *uri = chPound;
            *(uri+1) = chNull;
            XMLString::catString(uri, getEncryptedData()->getId());
            dataref->setURI(uri);
            delete[] uri;
        }
    }
}

XMLObject* EncryptedElementType::decrypt(
    const CredentialResolver& credResolver, const XMLCh* recipient, CredentialCriteria* criteria, bool requireAuthenticatedCipher
    ) const
{
    if (!getEncryptedData())
        throw DecryptionException("No encrypted data present.");
    opensaml::EncryptedKeyResolver ekr(*this);
    Decrypter decrypter(&credResolver, criteria, &ekr, requireAuthenticatedCipher);
    DOMDocumentFragment* frag = decrypter.decryptData(*getEncryptedData(), recipient);
    if (frag->hasChildNodes() && frag->getFirstChild()==frag->getLastChild()) {
        DOMNode* plaintext=frag->getFirstChild();
        if (plaintext->getNodeType()==DOMNode::ELEMENT_NODE) {
            // Import the tree into a new Document that we can bind to the unmarshalled object.
            XercesJanitor<DOMDocument> newdoc(XMLToolingConfig::getConfig().getParser().newDocument());
            DOMElement* treecopy;
            try {
                treecopy = static_cast<DOMElement*>(newdoc->importNode(plaintext, true));
            }
            catch (XMLException& ex) {
                frag->release();
                auto_ptr_char temp(ex.getMessage());
                throw DecryptionException(
                    string("Error importing decypted DOM into new document: ") + (temp.get() ? temp.get() : "no message")
                    );
            }
            frag->release();
            newdoc->appendChild(treecopy);
            auto_ptr<XMLObject> ret(XMLObjectBuilder::buildOneFromElement(treecopy, true));
            newdoc.release();
            return ret.release();
        }
    }
    frag->release();
    throw DecryptionException("Decryption did not result in a single element.");
}