Added additional logging/error handling in SHIRE and XMLOriginSiteMapper.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / shire / XMLOriginSiteMapper.java
1 /* 
2  * The Shibboleth License, Version 1. 
3  * Copyright (c) 2002 
4  * University Corporation for Advanced Internet Development, Inc. 
5  * All rights reserved
6  * 
7  * 
8  * Redistribution and use in source and binary forms, with or without 
9  * modification, are permitted provided that the following conditions are met:
10  * 
11  * Redistributions of source code must retain the above copyright notice, this 
12  * list of conditions and the following disclaimer.
13  * 
14  * Redistributions in binary form must reproduce the above copyright notice, 
15  * this list of conditions and the following disclaimer in the documentation 
16  * and/or other materials provided with the distribution, if any, must include 
17  * the following acknowledgment: "This product includes software developed by 
18  * the University Corporation for Advanced Internet Development 
19  * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement 
20  * may appear in the software itself, if and wherever such third-party 
21  * acknowledgments normally appear.
22  * 
23  * Neither the name of Shibboleth nor the names of its contributors, nor 
24  * Internet2, nor the University Corporation for Advanced Internet Development, 
25  * Inc., nor UCAID may be used to endorse or promote products derived from this 
26  * software without specific prior written permission. For written permission, 
27  * please contact shibboleth@shibboleth.org
28  * 
29  * Products derived from this software may not be called Shibboleth, Internet2, 
30  * UCAID, or the University Corporation for Advanced Internet Development, nor 
31  * may Shibboleth appear in their name, without prior written permission of the 
32  * University Corporation for Advanced Internet Development.
33  * 
34  * 
35  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
36  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
37  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
38  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK 
39  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE. 
40  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY 
41  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT, 
42  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
43  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
47  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49
50 package edu.internet2.middleware.shibboleth.shire;
51
52 import java.io.IOException;
53 import java.security.Key;
54 import java.security.KeyStore;
55 import java.security.PublicKey;
56 import java.util.HashMap;
57 import java.util.Iterator;
58 import java.util.Vector;
59
60 import javax.xml.parsers.DocumentBuilder;
61 import javax.xml.parsers.ParserConfigurationException;
62
63 import org.apache.log4j.Logger;
64 import org.apache.xml.security.c14n.Canonicalizer;
65 import org.apache.xml.security.exceptions.XMLSecurityException;
66 import org.apache.xml.security.keys.KeyInfo;
67 import org.apache.xml.security.signature.Reference;
68 import org.apache.xml.security.signature.SignedInfo;
69 import org.apache.xml.security.signature.XMLSignature;
70 import org.apache.xml.security.transforms.Transforms;
71 import org.w3c.dom.Document;
72 import org.w3c.dom.Element;
73 import org.w3c.dom.Node;
74 import org.w3c.dom.NodeList;
75 import org.xml.sax.SAXException;
76
77 import edu.internet2.middleware.shibboleth.common.OriginSiteMapper;
78 import edu.internet2.middleware.shibboleth.common.OriginSiteMapperException;
79 import edu.internet2.middleware.shibboleth.common.XML;
80
81 /**
82  *  OriginSiteMapper implementation using an XML file to populate an in-memory
83  *  database from an optionally-signed XML file
84  *
85  * @author     Scott Cantor
86  * @created    June 8, 2002
87  */
88 public class XMLOriginSiteMapper implements OriginSiteMapper {
89
90         private HashMap originSites = null;
91         private HashMap hsKeys = null;
92         private KeyStore ks = null;
93         private static Logger log = Logger.getLogger(XMLOriginSiteMapper.class.getName());
94
95         /**
96          *  Constructor for the XMLOriginSiteMapper object
97          *
98          * @param  registryURI               Tells where to find/download origin
99          *      site registry file
100          * @param  verifyKey                 Optional key to verify signature with
101          * @param  ks                        Key store containing the trusted roots
102          *      to be used by SHIRE
103          * @exception  Exception             Raised if the registry file cannot be
104          *      parsed and loaded
105          */
106
107         public XMLOriginSiteMapper(String registryURI, Key verifyKey, KeyStore ks)
108                 throws OriginSiteMapperException {
109                 this.ks = ks;
110                 originSites = new HashMap();
111                 hsKeys = new HashMap();
112
113                 DocumentBuilder builder = null;
114                 try {
115                         builder = org.opensaml.XML.parserPool.get();
116                         Document doc;
117                         doc = builder.parse(registryURI);
118                         log.info("Located site file (" +registryURI +").");
119                         Element e = doc.getDocumentElement();
120                         if (!XML.SHIB_NS.equals(e.getNamespaceURI()) || !"Sites".equals(e.getLocalName())) {
121                                 log.error("Construction requires a valid site file: (shib:Sites as root element)");
122                                 throw new OriginSiteMapperException("Construction requires a valid site file: (shib:Sites as root element)");
123                         }
124
125                         // Loop over the OriginSite elements.
126                         NodeList nlist = e.getElementsByTagNameNS(XML.SHIB_NS, "OriginSite");
127                         for (int i = 0; nlist != null && i < nlist.getLength(); i++) {
128                                 String os_name = ((Element) nlist.item(i)).getAttributeNS(null, "Name").trim();
129                                 if (os_name.length() == 0)
130                                         continue;
131
132                                 OriginSite os_obj = new OriginSite(os_name);
133                                 originSites.put(os_name, os_obj);
134
135                                 Node os_child = nlist.item(i).getFirstChild();
136                                 while (os_child != null) {
137                                         if (os_child.getNodeType() != Node.ELEMENT_NODE) {
138                                                 os_child = os_child.getNextSibling();
139                                                 continue;
140                                         }
141
142                                         // Process the various kinds of OriginSite children that we care about...
143                                         if (XML.SHIB_NS.equals(os_child.getNamespaceURI())
144                                                 && "HandleService".equals(os_child.getLocalName())) {
145                                                 String hs_name = ((Element) os_child).getAttributeNS(null, "Name").trim();
146                                                 if (hs_name.length() > 0) {
147                                                         os_obj.handleServices.add(hs_name);
148
149                                                         // Check for KeyInfo.
150                                                         Node ki = os_child.getFirstChild();
151                                                         while (ki != null && ki.getNodeType() != Node.ELEMENT_NODE)
152                                                                 ki = ki.getNextSibling();
153                                                         if (ki != null
154                                                                 && org.opensaml.XML.XMLSIG_NS.equals(ki.getNamespaceURI())
155                                                                 && "KeyInfo".equals(ki.getLocalName())) {
156                                                                 try {
157                                                                         KeyInfo kinfo = new KeyInfo((Element) ki, null);
158                                                                         PublicKey pubkey = kinfo.getPublicKey();
159                                                                         if (pubkey != null)
160                                                                                 hsKeys.put(hs_name, pubkey);
161                                                                 } catch (XMLSecurityException exc) {
162                                                                 }
163                                                         }
164                                                 }
165                                         } else if (
166                                                 XML.SHIB_NS.equals(os_child.getNamespaceURI())
167                                                         && "Domain".equals(os_child.getLocalName())) {
168                                                 String dom = os_child.getFirstChild().getNodeValue().trim();
169                                                 if (dom.length() > 0)
170                                                         os_obj.domains.add(dom);
171                                         }
172                                         os_child = os_child.getNextSibling();
173                                 }
174                         }
175
176                         if (verifyKey != null) {
177                                 log.info("Initialized with a key: attempting to verify document signature.");
178                                 validateSignature(verifyKey, e);
179                         } else {
180                                 log.info("Initialized without key: skipping signature verification.");
181                         }
182
183                 } catch (SAXException e) {
184                         log.error("Problem parsing site configuration" + e);
185                         throw new OriginSiteMapperException("Problem parsing site configuration" + e);
186                 } catch (IOException e) {
187                         log.error("Problem accessing site configuration" + e);
188                         throw new OriginSiteMapperException("Problem accessing site configuration" + e);
189                 } catch (ParserConfigurationException pce) {
190                         log.error("Parser configuration error" + pce);
191                         throw new OriginSiteMapperException("Parser configuration error" + pce);
192                 } finally {
193                         if (builder != null)
194                                 org.opensaml.XML.parserPool.put(builder);
195                 }
196         }
197
198         private void validateSignature(Key verifyKey, Element e) throws OriginSiteMapperException {
199
200                 Node n = e.getLastChild();
201                 while (n != null && n.getNodeType() != Node.ELEMENT_NODE)
202                         n = n.getPreviousSibling();
203
204                 if (n != null
205                         && org.opensaml.XML.XMLSIG_NS.equals(n.getNamespaceURI())
206                         && "Signature".equals(n.getLocalName())) {
207                                 log.info("Located signature in document... verifying.");
208                         try {
209                                 XMLSignature sig = new XMLSignature((Element) n, null);
210                                 if (sig.checkSignatureValue(verifyKey)) {
211                                         // Now we verify that what is signed is what we expect.
212                                         SignedInfo sinfo = sig.getSignedInfo();
213                                         if (sinfo.getLength() == 1
214                                                 && (sinfo
215                                                         .getCanonicalizationMethodURI()
216                                                         .equals(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS)
217                                                         || sinfo.getCanonicalizationMethodURI().equals(
218                                                                 Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS))) {
219                                                 Reference ref = sinfo.item(0);
220                                                 if (ref.getURI() == null || ref.getURI().equals("")) {
221                                                         Transforms trans = ref.getTransforms();
222                                                         if (trans.getLength() == 1
223                                                                 && trans.item(0).getURI().equals(Transforms.TRANSFORM_ENVELOPED_SIGNATURE))
224                                                                 log.info("Signature verification successful.");
225                                                                 return;
226                                                 }
227                                                 log.error(
228                                                         "Unable to verify signature on registry file: Unsupported dsig reference or transform data submitted with signature.");
229                                                 throw new OriginSiteMapperException("Unable to verify signature on registry file: Unsupported dsig reference or transform data submitted with signature.");
230                                         } else {
231                                                 log.error(
232                                                         "Unable to verify signature on registry file: Unsupported canonicalization method.");
233                                                 throw new OriginSiteMapperException("Unable to verify signature on registry file: Unsupported canonicalization method.");
234                                         }
235                                 } else {
236                                         log.error(
237                                                 "Unable to verify signature on registry file: signature cannot be verified with the specified key.");
238                                         throw new OriginSiteMapperException("Unable to verify signature on registry file: signature cannot be verified with the specified key.");
239                                 }
240                         } catch (Exception sigE) {
241                                 log.error(
242                                         "Unable to verify signature on registry file: An error occured while attempting to verify the signature:"
243                                                 + sigE);
244                                 throw new OriginSiteMapperException(
245                                         "Unable to verify signature on registry file: An error occured while attempting to verify the signature:"
246                                                 + sigE);
247                         }
248                 } else {
249                         log.error("Unable to verify signature on registry file: no signature found in document.");
250                         throw new OriginSiteMapperException("Unable to verify signature on registry file: no signature found in document.");
251                 }
252
253         }
254
255         /**
256          *  Provides an iterator over the trusted Handle Services for the specified
257          *  origin site
258          *
259          * @param  originSite  The DNS name of the origin site to query
260          * @return             An iterator over the Handle Service DNS names
261          */
262         public Iterator getHandleServiceNames(String originSite) {
263                 OriginSite o = (OriginSite) originSites.get(originSite);
264                 if (o != null)
265                         return o.handleServices.iterator();
266                 return null;
267         }
268
269         /**
270          *  Returns a preconfigured key to use in verifying a signature created by
271          *  the specified HS<P>
272          *
273          *  Any key returned is implicitly trusted and a certificate signed by
274          *  another trusted entity is not sought or required
275          *
276          * @param  handleService  Description of Parameter
277          * @return                A trusted key (probably public but could be
278          *      secret) or null
279          */
280         public Key getHandleServiceKey(String handleService) {
281                 return (Key) hsKeys.get(handleService);
282         }
283
284         /**
285          *  Provides an iterator over the security domain expressions for which the
286          *  specified origin site is considered to be authoritative
287          *
288          * @param  originSite  The DNS name of the origin site to query
289          * @return             An iterator over a set of regular expression strings
290          */
291         public Iterator getSecurityDomains(String originSite) {
292                 OriginSite o = (OriginSite) originSites.get(originSite);
293                 if (o != null)
294                         return o.domains.iterator();
295                 return null;
296         }
297
298         /**
299          *  Gets a key store containing certificate entries that are trusted to sign
300          *  Handle Service certificates that are encountered during processing<P>
301          *
302          *
303          *
304          * @return    A key store containing trusted certificate issuers
305          */
306         public KeyStore getTrustedRoots() {
307                 return ks;
308         }
309
310         private class OriginSite {
311
312                 private Vector domains = null;
313                 private Vector handleServices = null;
314
315                 private OriginSite(String name) {
316                         domains = new Vector();
317                         domains.add(name);
318                         handleServices = new Vector();
319                 }
320         }
321 }