b7bef565c89062890dd06990f897f95496dfe7ca
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / provider / BaseHandler.java
1 /*
2  * Copyright [2005] [University Corporation for Advanced Internet Development, Inc.]
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 package edu.internet2.middleware.shibboleth.idp.provider;
18
19 import java.io.IOException;
20 import java.security.cert.CertificateParsingException;
21 import java.security.cert.X509Certificate;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashSet;
25 import java.util.Iterator;
26 import java.util.List;
27
28 import javax.security.auth.x500.X500Principal;
29
30 import org.apache.log4j.Logger;
31 import org.bouncycastle.asn1.ASN1InputStream;
32 import org.bouncycastle.asn1.DERObject;
33 import org.bouncycastle.asn1.DERObjectIdentifier;
34 import org.bouncycastle.asn1.DERSequence;
35 import org.bouncycastle.asn1.DERSet;
36 import org.bouncycastle.asn1.DERString;
37 import org.w3c.dom.Element;
38 import org.w3c.dom.Node;
39 import org.w3c.dom.NodeList;
40
41 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
42 import edu.internet2.middleware.shibboleth.idp.IdPConfig;
43 import edu.internet2.middleware.shibboleth.idp.IdPProtocolHandler;
44
45 /**
46  * Functionality common to all <code>IdPProtocolHandler</code> implementation.
47  * 
48  * @author Walter Hoehn
49  */
50 public abstract class BaseHandler implements IdPProtocolHandler {
51
52         private static Logger log = Logger.getLogger(BaseHandler.class.getName());
53         private static final String CN_OID = "2.5.4.3";
54         private HashSet<String> locations = new HashSet<String>();
55
56         /**
57          * Required DOM-based constructor.
58          */
59         public BaseHandler(Element config) throws ShibbolethConfigurationException {
60
61                 // Make sure we have at least one location
62                 NodeList locations = config.getElementsByTagNameNS(IdPConfig.configNameSpace, "Location");
63                 if (locations.getLength() < 1) {
64                         log.error("The <ProtocolHandler/> element must contain at least one <Location/> element.");
65                         throw new ShibbolethConfigurationException("Unable to load ProtocolHandler.");
66                 }
67
68                 // Parse the locations
69                 for (int i = 0; i < locations.getLength(); i++) {
70                         Node tnode = ((Element) locations.item(i)).getFirstChild();
71                         if (tnode != null && tnode.getNodeType() == Node.TEXT_NODE) {
72                                 String rawURI = tnode.getNodeValue();
73
74                                 if (rawURI == null || rawURI.equals("")) {
75                                         log.error("The <Location/> element inside the <ProtocolHandler/> element must "
76                                                         + "contain a URI or regular expressions.");
77                                         throw new ShibbolethConfigurationException("Unable to load ProtocolHandler.");
78                                 }
79                                 this.locations.add(rawURI);
80
81                         } else {
82                                 log.error("The <Location/> element inside the <ProtocolHandler/> element must contain a "
83                                                 + "URI or regular expression.");
84                                 throw new ShibbolethConfigurationException("Unable to load ProtocolHandler.");
85                         }
86                 }
87         }
88
89         /*
90          * @see edu.internet2.middleware.shibboleth.idp.IdPProtocolHandler#getLocations()
91          */
92         public String[] getLocations() {
93
94                 return (String[]) locations.toArray(new String[0]);
95         }
96
97         protected static String getHostNameFromDN(X500Principal dn) {
98
99                 // Parse the ASN.1 representation of the dn and grab the last CN component that we find
100                 // We used to do this with the dn string, but the JDK's default parsing caused problems with some DNs
101                 try {
102                         ASN1InputStream asn1Stream = new ASN1InputStream(dn.getEncoded());
103                         DERObject parent = asn1Stream.readObject();
104
105                         if (!(parent instanceof DERSequence)) {
106                                 log.error("Unable to extract host name name from certificate subject DN: incorrect ASN.1 encoding.");
107                                 return null;
108                         }
109
110                         String cn = null;
111                         for (int i = 0; i < ((DERSequence) parent).size(); i++) {
112                                 DERObject dnComponent = ((DERSequence) parent).getObjectAt(i).getDERObject();
113                                 if (!(dnComponent instanceof DERSet)) {
114                                         log.debug("No DN components.");
115                                         continue;
116                                 }
117
118                                 // Each DN component is a set
119                                 for (int j = 0; j < ((DERSet) dnComponent).size(); j++) {
120                                         DERObject grandChild = ((DERSet) dnComponent).getObjectAt(j).getDERObject();
121
122                                         if (((DERSequence) grandChild).getObjectAt(0) != null
123                                                         && ((DERSequence) grandChild).getObjectAt(0).getDERObject() instanceof DERObjectIdentifier) {
124                                                 DERObjectIdentifier componentId = (DERObjectIdentifier) ((DERSequence) grandChild).getObjectAt(
125                                                                 0).getDERObject();
126
127                                                 if (CN_OID.equals(componentId.getId())) {
128                                                         // OK, this dn component is actually a cn attribute
129                                                         if (((DERSequence) grandChild).getObjectAt(1) != null
130                                                                         && ((DERSequence) grandChild).getObjectAt(1).getDERObject() instanceof DERString) {
131                                                                 cn = ((DERString) ((DERSequence) grandChild).getObjectAt(1).getDERObject()).getString();
132                                                         }
133                                                 }
134                                         }
135                                 }
136                         }
137                         asn1Stream.close();
138                         return cn;
139
140                 } catch (IOException e) {
141                         log.error("Unable to extract host name name from certificate subject DN: ASN.1 parsing failed: " + e);
142                         return null;
143                 }
144         }
145
146         protected static String[] getCredentialNames(X509Certificate cert) {
147
148                 ArrayList<String> names = new ArrayList<String>();
149                 names.add(cert.getSubjectX500Principal().getName(X500Principal.RFC2253));
150                 try {
151                         Collection altNames = cert.getSubjectAlternativeNames();
152                         if (altNames != null) {
153                                 for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
154                                         List altName = (List) nameIterator.next();
155                                         if (altName.get(0).equals(new Integer(2)) && altName.get(1) instanceof String) { // 2 is DNS
156                                                 names.add((String) altName.get(1));
157                                         } else if (altName.get(0).equals(new Integer(6)) && altName.get(1) instanceof String) { // 6 is URI
158                                                 names.add((String) altName.get(1));
159                                         }
160                                 }
161                         }
162                 } catch (CertificateParsingException e1) {
163                         log.error("Encountered an problem trying to extract Subject Alternate "
164                                         + "Name from supplied certificate: " + e1);
165                 }
166                 names.add(getHostNameFromDN(cert.getSubjectX500Principal()));
167                 return (String[]) names.toArray(new String[1]);
168         }
169 }