View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements. See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership. The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License. You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied. See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.ws.security.processor;
21  
22  import org.apache.ws.security.SAMLTokenPrincipal;
23  import org.apache.ws.security.WSConstants;
24  import org.apache.ws.security.WSDocInfo;
25  import org.apache.ws.security.WSSecurityEngineResult;
26  import org.apache.ws.security.WSSecurityException;
27  import org.apache.ws.security.components.crypto.AlgorithmSuite;
28  import org.apache.ws.security.components.crypto.AlgorithmSuiteValidator;
29  import org.apache.ws.security.handler.RequestData;
30  import org.apache.ws.security.saml.SAMLKeyInfo;
31  import org.apache.ws.security.saml.SAMLUtil;
32  import org.apache.ws.security.saml.ext.AssertionWrapper;
33  import org.apache.ws.security.util.DOM2Writer;
34  import org.apache.ws.security.validate.Credential;
35  import org.apache.ws.security.validate.Validator;
36  
37  import org.opensaml.xml.signature.KeyInfo;
38  import org.opensaml.xml.signature.Signature;
39  import org.w3c.dom.Element;
40  
41  import java.security.NoSuchProviderException;
42  import java.security.PublicKey;
43  import java.util.List;
44  
45  import javax.xml.crypto.MarshalException;
46  import javax.xml.crypto.dsig.XMLSignature;
47  import javax.xml.crypto.dsig.XMLSignatureFactory;
48  import javax.xml.crypto.dsig.XMLValidateContext;
49  import javax.xml.crypto.dsig.dom.DOMValidateContext;
50  import javax.xml.namespace.QName;
51  
52  public class SAMLTokenProcessor implements Processor {
53      private static org.apache.commons.logging.Log log = 
54          org.apache.commons.logging.LogFactory.getLog(SAMLTokenProcessor.class);
55      private XMLSignatureFactory signatureFactory;
56  
57      public SAMLTokenProcessor() {
58          // Try to install the Santuario Provider - fall back to the JDK provider if this does
59          // not work
60          try {
61              signatureFactory = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig");
62          } catch (NoSuchProviderException ex) {
63              signatureFactory = XMLSignatureFactory.getInstance("DOM");
64          }
65      }
66  
67      public List<WSSecurityEngineResult> handleToken(
68          Element elem, 
69          RequestData data, 
70          WSDocInfo wsDocInfo 
71      ) throws WSSecurityException {
72          if (log.isDebugEnabled()) {
73              log.debug("Found SAML Assertion element");
74          }
75          
76          Validator validator = 
77              data.getValidator(new QName(elem.getNamespaceURI(), elem.getLocalName()));
78          Credential credential = handleSAMLToken(elem, data, validator, wsDocInfo);
79          AssertionWrapper assertion = credential.getAssertion();
80          if (log.isDebugEnabled()) {
81              log.debug("SAML Assertion issuer " + assertion.getIssuerString());
82              log.debug(DOM2Writer.nodeToString(elem));
83          }
84          
85          // See if the token has been previously processed
86          String id = assertion.getId();
87          Element foundElement = wsDocInfo.getTokenElement(id);
88          if (elem.equals(foundElement)) {
89              WSSecurityEngineResult result = wsDocInfo.getResult(id);
90              return java.util.Collections.singletonList(result);
91          } else if (foundElement != null) {
92              throw new WSSecurityException(
93                  WSSecurityException.INVALID_SECURITY_TOKEN, "duplicateError"
94              );
95          }
96  
97          wsDocInfo.addTokenElement(elem);
98          WSSecurityEngineResult result = null;
99          if (assertion.isSigned()) {
100             result = new WSSecurityEngineResult(WSConstants.ST_SIGNED, assertion);
101         } else {
102             result = new WSSecurityEngineResult(WSConstants.ST_UNSIGNED, assertion);
103         }
104         
105         result.put(WSSecurityEngineResult.TAG_ID, assertion.getId());
106 
107         if (validator != null) {
108             result.put(WSSecurityEngineResult.TAG_VALIDATED_TOKEN, Boolean.TRUE);
109             if (credential.getTransformedToken() != null) {
110                 result.put(
111                     WSSecurityEngineResult.TAG_TRANSFORMED_TOKEN, credential.getTransformedToken()
112                 );
113                 SAMLTokenPrincipal samlPrincipal = 
114                     new SAMLTokenPrincipal(credential.getTransformedToken());
115                 result.put(WSSecurityEngineResult.TAG_PRINCIPAL, samlPrincipal);
116             } else if (credential.getPrincipal() != null) {
117                 result.put(WSSecurityEngineResult.TAG_PRINCIPAL, credential.getPrincipal());
118             } else {
119                 result.put(WSSecurityEngineResult.TAG_PRINCIPAL, new SAMLTokenPrincipal(assertion));
120             }
121         }
122         wsDocInfo.addResult(result);
123         return java.util.Collections.singletonList(result);
124     }
125 
126     public Credential handleSAMLToken(
127         Element token, 
128         RequestData data,
129         Validator validator,
130         WSDocInfo docInfo
131     ) throws WSSecurityException {
132         AssertionWrapper assertion = new AssertionWrapper(token);
133         if (assertion.isSigned()) {
134             // Check for compliance against the defined AlgorithmSuite
135             AlgorithmSuite algorithmSuite = data.getSamlAlgorithmSuite();
136             
137             Signature sig = assertion.getSignature();
138             KeyInfo keyInfo = sig.getKeyInfo();
139             SAMLKeyInfo samlKeyInfo = 
140                 SAMLUtil.getCredentialDirectlyFromKeyInfo(
141                     keyInfo.getDOM(), data
142                 );
143             
144             if (algorithmSuite != null) {
145                 AlgorithmSuiteValidator algorithmSuiteValidator = new
146                     AlgorithmSuiteValidator(algorithmSuite);
147 
148                 PublicKey key = null;
149                 if (samlKeyInfo.getCerts() != null && samlKeyInfo.getCerts()[0] != null) {
150                     key = samlKeyInfo.getCerts()[0].getPublicKey();
151                 } else if (samlKeyInfo.getPublicKey() != null) {
152                     key = samlKeyInfo.getPublicKey();
153                 } else {
154                     throw new WSSecurityException(
155                         WSSecurityException.FAILURE, "invalidSAMLsecurity",
156                         new Object[]{"cannot get certificate or key"}
157                     );
158                 }
159             
160                 // Not checking signature here, just marshalling into an XMLSignature
161                 // structure for testing the transform/digest algorithms etc.
162                 XMLValidateContext context = new DOMValidateContext(key, sig.getDOM());
163                 context.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.TRUE);
164 
165                 XMLSignature xmlSignature;
166                 try {
167                     xmlSignature = signatureFactory.unmarshalXMLSignature(context);
168                 } catch (MarshalException ex) {
169                     throw new WSSecurityException(
170                         WSSecurityException.FAILED_CHECK, "invalidSAMLsecurity", 
171                         new Object[]{"cannot get certificate or key"}, ex
172                     );
173                 }
174 
175                 algorithmSuiteValidator.checkSignatureAlgorithms(xmlSignature);
176                 algorithmSuiteValidator.checkAsymmetricKeyLength(key);
177             }
178 
179             assertion.verifySignature(samlKeyInfo);
180         }
181         // Parse the HOK subject if it exists
182         assertion.parseHOKSubject(data, docInfo);
183             
184         // Now delegate the rest of the verification to the Validator
185         Credential credential = new Credential();
186         credential.setAssertion(assertion);
187         if (validator != null) {
188             return validator.validate(credential, data);
189         }
190         return credential;
191     }
192 
193 }