Next integration phase, metadata and trust conversion.
[shibboleth/cpp-sp.git] / shib-target / ArtifactMapper.cpp
1 /*
2  *  Copyright 2001-2005 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 /* ArtifactMapper.cpp - a ShibTarget-aware SAML artifact->binding mapper
18
19    Scott Cantor
20    2/20/05
21
22    $History:$
23 */
24
25 #include "internal.h"
26 #include <saml/binding/SAMLArtifact.h>
27
28 using namespace shibsp;
29 using namespace shibtarget;
30 using namespace saml;
31 using namespace opensaml::saml2md;
32 using namespace xmltooling;
33 using namespace log4cpp;
34 using namespace std;
35
36 SAMLResponse* STArtifactMapper::resolve(SAMLRequest* request)
37 {
38     Category& log=Category::getInstance("shibtarget.ArtifactMapper");
39     
40     // First do a search for the issuer.
41     SAMLArtifact* artifact=request->getArtifacts().next();
42     auto_ptr<opensaml::SAMLArtifact> os2art(opensaml::SAMLArtifact::parse(artifact->encode().c_str()));
43
44     MetadataProvider* m=m_app->getMetadataProvider();
45     const EntityDescriptor* entity=m->getEntityDescriptor(os2art.get());
46     if (!entity) {
47         log.error(
48             "metadata lookup failed, unable to determine issuer of artifact (0x%s)",
49             opensaml::SAMLArtifact::toHex(artifact->getBytes()).c_str()
50             );
51         throw MetadataException("Metadata lookup failed, unable to determine artifact issuer");
52     }
53     
54     xmltooling::auto_ptr_char issuer(entity->getEntityID());
55     log.info("lookup succeeded, artifact issued by (%s)", issuer.get());
56     
57     // Sign it?
58     const PropertySet* credUse=m_app->getCredentialUse(entity);
59     pair<bool,bool> signRequest=credUse ? credUse->getBool("signRequest") : make_pair(false,false);
60     pair<bool,const char*> signatureAlg=credUse ? credUse->getString("signatureAlg") : pair<bool,const char*>(false,NULL);
61     if (!signatureAlg.first)
62         signatureAlg.second=URI_ID_RSA_SHA1;
63     pair<bool,const char*> digestAlg=credUse ? credUse->getString("digestAlg") : pair<bool,const char*>(false,NULL);
64     if (!digestAlg.first)
65         digestAlg.second=URI_ID_SHA1;
66     pair<bool,bool> signedResponse=credUse ? credUse->getBool("signedResponse") : make_pair(false,false);
67     pair<bool,const char*> signingCred=credUse ? credUse->getString("Signing") : pair<bool,const char*>(false,NULL);
68     if (signRequest.first && signRequest.second && signingCred.first) {
69         if (request->getMinorVersion()==1) {
70             shibboleth::Credentials creds(ShibTargetConfig::getConfig().getINI()->getCredentialsProviders());
71             const shibboleth::ICredResolver* cr=creds.lookup(signingCred.second);
72             if (cr)
73                 request->sign(cr->getKey(),cr->getCertificates(),signatureAlg.second,digestAlg.second);
74             else
75                 log.error("unable to sign artifact request, specified credential (%s) was not found",signingCred.second);
76         }
77         else
78             log.error("unable to sign SAML 1.0 artifact request, only SAML 1.1 defines signing adequately");
79     }
80
81         SAMLResponse* response = NULL;
82         bool authenticated = false;
83     static const XMLCh https[] = {chLatin_h, chLatin_t, chLatin_t, chLatin_p, chLatin_s, chColon, chNull};
84
85     // Depends on type of artifact.
86     const SAMLArtifactType0001* type1=dynamic_cast<const SAMLArtifactType0001*>(artifact);
87     if (type1) {
88         // With type 01, any endpoint will do.
89         const IDPSSODescriptor* idp=entity->getIDPSSODescriptor(
90             request->getMinorVersion()==1 ? samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM
91             );
92         if (idp) {
93                     ShibHTTPHook::ShibHTTPHookCallContext callCtx(credUse,idp);
94             const vector<ArtifactResolutionService*>& endpoints=idp->getArtifactResolutionServices();
95             for (vector<ArtifactResolutionService*>::const_iterator ep=endpoints.begin(); !response && ep!=endpoints.end(); ++ep) {
96                 const SAMLBinding* binding = m_app->getBinding((*ep)->getBinding());
97                 if (!binding) {
98                     xmltooling::auto_ptr_char prot((*ep)->getBinding());
99                     log.warn("skipping binding on unsupported protocol (%s)", prot.get());
100                     continue;
101                 }
102                         try {
103                             response = binding->send((*ep)->getLocation(),*request,&callCtx);
104                             if (log.isDebugEnabled())
105                                 log.debugStream() << "SAML response from artifact request:\n" << *response << CategoryStream::ENDLINE;
106                             
107                             if (!response->getAssertions().hasNext()) {
108                                 delete response;
109                                 throw FatalProfileException("No SAML assertions returned in response to artifact profile request.");
110                             }
111                             authenticated = callCtx.isAuthenticated() && !XMLString::compareNString((*ep)->getLocation(),https,6);
112                         }
113                         catch (XMLToolingException& ex) {
114                                 annotateException(&ex,idp); // rethrows it
115                         }
116                 catch (exception& ex) {
117                     opensaml::BindingException ex2(ex.what());
118                     annotateException(&ex2,idp); // rethrows it
119                 }
120             }
121         }
122     }
123     else {
124         const SAMLArtifactType0002* type2=dynamic_cast<const SAMLArtifactType0002*>(artifact);
125         if (type2) {
126             // With type 02, we have to find the matching location.
127             const IDPSSODescriptor* idp=entity->getIDPSSODescriptor(
128                 request->getMinorVersion()==1 ? samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM
129                 );
130             if (idp) {
131                     ShibHTTPHook::ShibHTTPHookCallContext callCtx(credUse,idp);
132                 const vector<ArtifactResolutionService*>& endpoints=idp->getArtifactResolutionServices();
133                 for (vector<ArtifactResolutionService*>::const_iterator ep=endpoints.begin(); !response && ep!=endpoints.end(); ++ep) {
134                     xmltooling::auto_ptr_char loc((*ep)->getLocation());
135                     if (strcmp(loc.get(),type2->getSourceLocation()))
136                         continue;
137                         const SAMLBinding* binding = m_app->getBinding((*ep)->getBinding());
138                         if (!binding) {
139                             xmltooling::auto_ptr_char prot((*ep)->getBinding());
140                             log.warn("skipping binding on unsupported protocol (%s)", prot.get());
141                             continue;
142                         }
143                                 try {
144                                     response = binding->send((*ep)->getLocation(),*request,&callCtx);
145                                     if (log.isDebugEnabled())
146                                         log.debugStream() << "SAML response from artifact request:\n" << *response << CategoryStream::ENDLINE;
147                                     
148                                     if (!response->getAssertions().hasNext()) {
149                                         delete response;
150                                         throw FatalProfileException("No SAML assertions returned in response to artifact profile request.");
151                                     }
152                         authenticated = callCtx.isAuthenticated() && !XMLString::compareNString((*ep)->getLocation(),https,6);
153                                 }
154                             catch (XMLToolingException& ex) {
155                                     annotateException(&ex,idp); // rethrows it
156                             }
157                     catch (exception& ex) {
158                         opensaml::BindingException ex2(ex.what());
159                         annotateException(&ex2,idp); // rethrows it
160                     }
161                 }
162             }
163         }
164         else {
165             log.error("unrecognized artifact type (0x%s)", SAMLArtifact::toHex(artifact->getTypeCode()).c_str());
166             throw xmltooling::UnknownExtensionException(
167                 string("Received unrecognized artifact type (0x") + SAMLArtifact::toHex(artifact->getTypeCode()) + ")"
168                 );
169         }
170     }
171     
172     if (!response) {
173             log.error("unable to locate acceptable binding/endpoint to resolve artifact");
174             MetadataException ex("Unable to locate acceptable binding/endpoint to resolve artifact.");
175             annotateException(&ex,entity); // throws it
176     }
177     else if (!response->isSigned()) {
178         if (!authenticated || (signedResponse.first && signedResponse.second)) {
179                 log.error("unsigned response obtained, but it must be signed.");
180                 XMLSecurityException ex("Unable to obtain a signed response from artifact request.");
181                     annotateException(&ex,entity); // throws it
182         }
183     }
184     
185     return response;
186 }