Change API to permit session initiators to modify the entityID mid-chain.
[shibboleth/sp.git] / shibsp / handler / impl / SAMLDSSessionInitiator.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  * SAMLDSSessionInitiator.cpp
19  * 
20  * SAML Discovery Service support.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "SPRequest.h"
27 #include "handler/AbstractHandler.h"
28 #include "handler/SessionInitiator.h"
29
30 #include <xmltooling/XMLToolingConfig.h>
31 #include <xmltooling/impl/AnyElement.h>
32 #include <xmltooling/util/URLEncoder.h>
33
34 using namespace shibsp;
35 using namespace opensaml;
36 using namespace xmltooling;
37 using namespace std;
38
39 #ifndef SHIBSP_LITE
40 using namespace opensaml::saml2md;
41 #endif
42
43 namespace shibsp {
44
45 #if defined (_MSC_VER)
46     #pragma warning( push )
47     #pragma warning( disable : 4250 )
48 #endif
49
50     class SHIBSP_DLLLOCAL SAMLDSSessionInitiator : public SessionInitiator, public AbstractHandler
51     {
52     public:
53         SAMLDSSessionInitiator(const DOMElement* e, const char* appId)
54                 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAMLDS")), m_url(NULL), m_returnParam(NULL)
55 #ifndef SHIBSP_LITE
56                     ,m_discoNS("urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol")
57 #endif
58         {
59             pair<bool,const char*> url = getString("URL");
60             if (!url.first)
61                 throw ConfigurationException("SAMLDS SessionInitiator requires a URL property.");
62             m_url = url.second;
63             url = getString("entityIDParam");
64             if (url.first)
65                 m_returnParam = url.second;
66         }
67         virtual ~SAMLDSSessionInitiator() {}
68         
69         pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
70
71 #ifndef SHIBSP_LITE
72         void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
73             static const XMLCh LOCAL_NAME[] = UNICODE_LITERAL_17(D,i,s,c,o,v,e,r,y,R,e,s,p,o,n,s,e);
74             const char* loc = getString("Location").second;
75             string hurl(handlerURL);
76             if (*loc != '/')
77                 hurl += '/';
78             hurl += loc;
79             auto_ptr_XMLCh widen(hurl.c_str());
80             ElementProxy* ep = new AnyElementImpl(m_discoNS.get(), LOCAL_NAME);
81             ep->setAttribute(QName(NULL,EndpointType::LOCATION_ATTRIB_NAME), widen.get());
82             ep->setAttribute(QName(NULL,EndpointType::BINDING_ATTRIB_NAME), getXMLString("Binding").second);
83             pair<bool,const XMLCh*> ix = getXMLString("index");
84             ep->setAttribute(QName(NULL,IndexedEndpointType::INDEX_ATTRIB_NAME), ix.first ? ix.second : xmlconstants::XML_ONE);
85             
86             Extensions* ext = role.getExtensions();
87             if (!ext) {
88                 ext = ExtensionsBuilder::buildExtensions();
89                 role.setExtensions(ext);
90             }
91             ext->getUnknownXMLObjects().push_back(ep);
92         }
93 #endif
94
95     private:
96         const char* m_url;
97         const char* m_returnParam;
98 #ifndef SHIBSP_LITE
99         auto_ptr_XMLCh m_discoNS;
100 #endif
101     };
102
103 #if defined (_MSC_VER)
104     #pragma warning( pop )
105 #endif
106
107     SessionInitiator* SHIBSP_DLLLOCAL SAMLDSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
108     {
109         return new SAMLDSSessionInitiator(p.first, p.second);
110     }
111
112 };
113
114 pair<bool,long> SAMLDSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
115 {
116     // The IdP CANNOT be specified for us to run. Otherwise, we'd be redirecting to a DS
117     // anytime the IdP's metadata was wrong.
118     if (!entityID.empty())
119         return make_pair(false,0L);
120
121     string target;
122     const char* option;
123     bool isPassive=false;
124     const Application& app=request.getApplication();
125
126     if (isHandler) {
127         option = request.getParameter("SAMLDS");
128         if (option && !strcmp(option,"1")) {
129             saml2md::MetadataException ex("No identity provider was selected by user.");
130             ex.addProperty("statusCode", "urn:oasis:names:tc:SAML:2.0:status:Requester");
131             ex.addProperty("statusCode2", "urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP");
132             ex.raise();
133         }
134         
135         option = request.getParameter("target");
136         if (option)
137             target = option;
138         recoverRelayState(request.getApplication(), request, request, target, false);
139
140         option = request.getParameter("isPassive");
141         if (option)
142             isPassive = !strcmp(option,"true");
143     }
144     else {
145         // We're running as a "virtual handler" from within the filter.
146         // The target resource is the current one and everything else is
147         // defaulted or set by content policy.
148         target=request.getRequestURL();
149         pair<bool,bool> passopt = getBool("isPassive");
150         isPassive = passopt.first && passopt.second;
151     }
152
153     m_log.debug("sending request to SAMLDS (%s)", m_url);
154
155     // Compute the return URL. We start with a self-referential link.
156     string returnURL=request.getHandlerURL(target.c_str());
157     pair<bool,const char*> thisloc = getString("Location");
158     if (thisloc.first) returnURL += thisloc.second;
159     returnURL += "?SAMLDS=1"; // signals us not to loop if we get no answer back
160
161     if (isHandler) {
162         // We may already have RelayState set if we looped back here,
163         // but just in case target is a resource, we reset it back.
164         option = request.getParameter("target");
165         if (option)
166             target = option;
167     }
168     preserveRelayState(request.getApplication(), request, target);
169
170     const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
171     if (isHandler) {
172         // Now the hard part. The base assumption is to append the entire query string, if any,
173         // to the self-link. But we want to replace target with the RelayState-preserved value
174         // to hide it from the DS.
175         const char* query = request.getQueryString();
176         if (query) {
177             // See if it starts with target.
178             if (!strncmp(query, "target=", 7)) {
179                 // We skip this altogether and advance the query past it to the first separator.
180                 query = strchr(query, '&');
181                 // If we still have more, just append it.
182                 if (query && *(++query))
183                     returnURL = returnURL + '&' + query;
184             }
185             else {
186                 // There's something in the query before target appears, so we have to find it.
187                 thisloc.second = strstr(query,"&target=");
188                 if (thisloc.second) {
189                     // We found it, so first append everything up to it.
190                     returnURL += '&';
191                     returnURL.append(query, thisloc.second - query);
192                     query = thisloc.second + 8; // move up just past the equals sign.
193                     thisloc.second = strchr(query, '&');
194                     if (thisloc.second)
195                         returnURL += thisloc.second;
196                 }
197                 else {
198                     // No target in the existing query, so just append it as is.
199                     returnURL = returnURL + '&' + query;
200                 }
201             }
202         }
203
204         // Now append the sanitized target as needed.
205         if (!target.empty())
206             returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
207     }
208     else if (!target.empty()) {
209         // For a virtual handler, we just append target to the return link.
210         returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());;
211     }
212
213     string req=string(m_url) + (strchr(m_url,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
214         "&return=" + urlenc->encode(returnURL.c_str());
215     if (m_returnParam)
216         req = req + "&returnIDParam=" + m_returnParam;
217     if (isPassive)
218         req += "&isPassive=true";
219
220     return make_pair(true, request.sendRedirect(req.c_str()));
221 }