8e2c22a9379ef5896e8aecf99b656c6c3d06951f
[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.xml.security.c14n.Canonicalizer;
64 import org.apache.xml.security.exceptions.XMLSecurityException;
65 import org.apache.xml.security.keys.KeyInfo;
66 import org.apache.xml.security.signature.Reference;
67 import org.apache.xml.security.signature.SignedInfo;
68 import org.apache.xml.security.signature.XMLSignature;
69 import org.apache.xml.security.transforms.Transforms;
70 import org.w3c.dom.Document;
71 import org.w3c.dom.Element;
72 import org.w3c.dom.Node;
73 import org.w3c.dom.NodeList;
74 import org.xml.sax.SAXException;
75
76 import edu.internet2.middleware.shibboleth.common.OriginSiteMapper;
77 import edu.internet2.middleware.shibboleth.common.OriginSiteMapperException;
78 import edu.internet2.middleware.shibboleth.common.XML;
79
80 /**
81  *  OriginSiteMapper implementation using an XML file to populate an in-memory
82  *  database from an optionally-signed XML file
83  *
84  * @author     Scott Cantor
85  * @created    June 8, 2002
86  */
87 public class XMLOriginSiteMapper implements OriginSiteMapper {
88
89         private HashMap originSites = null;
90         private HashMap hsKeys = null;
91         private KeyStore ks = null;
92
93         /**
94          *  Constructor for the XMLOriginSiteMapper object
95          *
96          * @param  registryURI               Tells where to find/download origin
97          *      site registry file
98          * @param  verifyKey                 Optional key to verify signature with
99          * @param  ks                        Key store containing the trusted roots
100          *      to be used by SHIRE
101          * @exception  Exception             Raised if the registry file cannot be
102          *      parsed and loaded
103          */
104
105         public XMLOriginSiteMapper(String registryURI, Key verifyKey, KeyStore ks)
106                 throws OriginSiteMapperException {
107                 this.ks = ks;
108                 originSites = new HashMap();
109                 hsKeys = new HashMap();
110
111                 DocumentBuilder builder = null;
112                 try {
113                         builder = org.opensaml.XML.parserPool.get();
114                         Document doc;
115                         doc = builder.parse(registryURI);
116                         Element e = doc.getDocumentElement();
117                         if (!XML.SHIB_NS.equals(e.getNamespaceURI()) || !"Sites".equals(e.getLocalName()))
118                                 throw new OriginSiteMapperException("XMLOriginSiteMapper() requires shib:Sites as root element");
119
120                         // Loop over the OriginSite elements.
121                         NodeList nlist = e.getElementsByTagNameNS(XML.SHIB_NS, "OriginSite");
122                         for (int i = 0; nlist != null && i < nlist.getLength(); i++) {
123                                 String os_name = ((Element) nlist.item(i)).getAttributeNS(null, "Name").trim();
124                                 if (os_name.length() == 0)
125                                         continue;
126
127                                 OriginSite os_obj = new OriginSite(os_name);
128                                 originSites.put(os_name, os_obj);
129
130                                 Node os_child = nlist.item(i).getFirstChild();
131                                 while (os_child != null) {
132                                         if (os_child.getNodeType() != Node.ELEMENT_NODE) {
133                                                 os_child = os_child.getNextSibling();
134                                                 continue;
135                                         }
136
137                                         // Process the various kinds of OriginSite children that we care about...
138                                         if (XML.SHIB_NS.equals(os_child.getNamespaceURI())
139                                                 && "HandleService".equals(os_child.getLocalName())) {
140                                                 String hs_name = ((Element) os_child).getAttributeNS(null, "Name").trim();
141                                                 if (hs_name.length() > 0) {
142                                                         os_obj.handleServices.add(hs_name);
143
144                                                         // Check for KeyInfo.
145                                                         Node ki = os_child.getFirstChild();
146                                                         while (ki != null && ki.getNodeType() != Node.ELEMENT_NODE)
147                                                                 ki = ki.getNextSibling();
148                                                         if (ki != null
149                                                                 && org.opensaml.XML.XMLSIG_NS.equals(ki.getNamespaceURI())
150                                                                 && "KeyInfo".equals(ki.getLocalName())) {
151                                                                 try {
152                                                                         KeyInfo kinfo = new KeyInfo((Element) ki, null);
153                                                                         PublicKey pubkey = kinfo.getPublicKey();
154                                                                         if (pubkey != null)
155                                                                                 hsKeys.put(hs_name, pubkey);
156                                                                 } catch (XMLSecurityException exc) {
157                                                                 }
158                                                         }
159                                                 }
160                                         } else if (
161                                                 XML.SHIB_NS.equals(os_child.getNamespaceURI())
162                                                         && "Domain".equals(os_child.getLocalName())) {
163                                                 String dom = os_child.getFirstChild().getNodeValue().trim();
164                                                 if (dom.length() > 0)
165                                                         os_obj.domains.add(dom);
166                                         }
167                                         os_child = os_child.getNextSibling();
168                                 }
169                         }
170
171                         if (verifyKey == null)
172                                 return;
173
174                         Node n = e.getLastChild();
175                         while (n != null && n.getNodeType() != Node.ELEMENT_NODE)
176                                 n = n.getPreviousSibling();
177
178                         if (n != null
179                                 && org.opensaml.XML.XMLSIG_NS.equals(n.getNamespaceURI())
180                                 && "Signature".equals(n.getLocalName())) {
181                                 try {
182                                         XMLSignature sig = new XMLSignature((Element) n, null);
183                                         if (sig.checkSignatureValue(verifyKey)) {
184                                                 // Now we verify that what is signed is what we expect.
185                                                 SignedInfo sinfo = sig.getSignedInfo();
186                                                 if (sinfo.getLength() == 1
187                                                         && (sinfo
188                                                                 .getCanonicalizationMethodURI()
189                                                                 .equals(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS)
190                                                                 || sinfo.getCanonicalizationMethodURI().equals(
191                                                                         Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS)))
192                                                         //                                sinfo.getCanonicalizationMethodURI().equals(Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS) ||
193                                                         //                         sinfo.getCanonicalizationMethodURI().equals(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS))
194                                                         {
195                                                         Reference ref = sinfo.item(0);
196                                                         if (ref.getURI() == null || ref.getURI().equals("")) {
197                                                                 Transforms trans = ref.getTransforms();
198                                                                 if (trans.getLength() == 1
199                                                                         && trans.item(0).getURI().equals(Transforms.TRANSFORM_ENVELOPED_SIGNATURE))
200                                                                         return;
201                                                         }
202                                                 }
203                                         }
204                                 } catch (Exception sigE) {
205                                         throw new OriginSiteMapperException(
206                                                 "Unable to verify signature on registry file: Site file not signed correctly with specified key:"
207                                                         + sigE);
208                                 }
209                         }
210                         throw new OriginSiteMapperException("Unable to verify signature on registry file: no signature found.");
211                 } catch (SAXException e) {
212                         throw new OriginSiteMapperException("Problem parsing site configuration" + e);
213                 } catch (IOException e) {
214                         throw new OriginSiteMapperException("Problem accessing site configuration" + e);
215                 } catch (ParserConfigurationException pce) {
216                         throw new OriginSiteMapperException("Parser configuration error" + pce);
217                 } finally {
218                         if (builder != null)
219                                 org.opensaml.XML.parserPool.put(builder);
220                 }
221         }
222
223         /**
224          *  Provides an iterator over the trusted Handle Services for the specified
225          *  origin site
226          *
227          * @param  originSite  The DNS name of the origin site to query
228          * @return             An iterator over the Handle Service DNS names
229          */
230         public Iterator getHandleServiceNames(String originSite) {
231                 OriginSite o = (OriginSite) originSites.get(originSite);
232                 if (o != null)
233                         return o.handleServices.iterator();
234                 return null;
235         }
236
237         /**
238          *  Returns a preconfigured key to use in verifying a signature created by
239          *  the specified HS<P>
240          *
241          *  Any key returned is implicitly trusted and a certificate signed by
242          *  another trusted entity is not sought or required
243          *
244          * @param  handleService  Description of Parameter
245          * @return                A trusted key (probably public but could be
246          *      secret) or null
247          */
248         public Key getHandleServiceKey(String handleService) {
249                 return (Key) hsKeys.get(handleService);
250         }
251
252         /**
253          *  Provides an iterator over the security domain expressions for which the
254          *  specified origin site is considered to be authoritative
255          *
256          * @param  originSite  The DNS name of the origin site to query
257          * @return             An iterator over a set of regular expression strings
258          */
259         public Iterator getSecurityDomains(String originSite) {
260                 OriginSite o = (OriginSite) originSites.get(originSite);
261                 if (o != null)
262                         return o.domains.iterator();
263                 return null;
264         }
265
266         /**
267          *  Gets a key store containing certificate entries that are trusted to sign
268          *  Handle Service certificates that are encountered during processing<P>
269          *
270          *
271          *
272          * @return    A key store containing trusted certificate issuers
273          */
274         public KeyStore getTrustedRoots() {
275                 return ks;
276         }
277
278         private class OriginSite {
279
280                 private Vector domains = null;
281                 private Vector handleServices = null;
282
283                 private OriginSite(String name) {
284                         domains = new Vector();
285                         domains.add(name);
286                         handleServices = new Vector();
287                 }
288         }
289 }