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.validate;
21  
22  import java.io.IOException;
23  
24  import javax.security.auth.callback.Callback;
25  import javax.security.auth.callback.UnsupportedCallbackException;
26  
27  import org.apache.ws.security.WSConstants;
28  import org.apache.ws.security.WSPasswordCallback;
29  import org.apache.ws.security.WSSConfig;
30  import org.apache.ws.security.WSSecurityException;
31  import org.apache.ws.security.handler.RequestData;
32  import org.apache.ws.security.message.token.UsernameToken;
33  import org.apache.ws.security.util.Base64;
34  
35  /**
36   * This class validates a processed UsernameToken, extracted from the Credential passed to
37   * the validate method.
38   */
39  public class UsernameTokenValidator implements Validator {
40      
41      private static org.apache.commons.logging.Log log = 
42          org.apache.commons.logging.LogFactory.getLog(UsernameTokenValidator.class);
43      
44      /**
45       * Validate the credential argument. It must contain a non-null UsernameToken. A 
46       * CallbackHandler implementation is also required to be set.
47       * 
48       * If the password type is either digest or plaintext, it extracts a password from the 
49       * CallbackHandler and then compares the passwords appropriately.
50       * 
51       * If the password is null it queries a hook to allow the user to validate UsernameTokens
52       * of this type. 
53       * 
54       * @param credential the Credential to be validated
55       * @param data the RequestData associated with the request
56       * @throws WSSecurityException on a failed validation
57       */
58      public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
59          if (credential == null || credential.getUsernametoken() == null) {
60              throw new WSSecurityException(WSSecurityException.FAILURE, "noCredential");
61          }
62          
63          boolean handleCustomPasswordTypes = false;
64          boolean passwordsAreEncoded = false;
65          String requiredPasswordType = null;
66          WSSConfig wssConfig = data.getWssConfig();
67          if (wssConfig != null) {
68              handleCustomPasswordTypes = wssConfig.getHandleCustomPasswordTypes();
69              passwordsAreEncoded = wssConfig.getPasswordsAreEncoded();
70              requiredPasswordType = wssConfig.getRequiredPasswordType();
71          }
72          
73          UsernameToken usernameToken = credential.getUsernametoken();
74          usernameToken.setPasswordsAreEncoded(passwordsAreEncoded);
75          
76          String pwType = usernameToken.getPasswordType();
77          if (log.isDebugEnabled()) {
78              log.debug("UsernameToken user " + usernameToken.getName());
79              log.debug("UsernameToken password type " + pwType);
80          }
81          
82          if (requiredPasswordType != null && !requiredPasswordType.equals(pwType)) {
83              if (log.isDebugEnabled()) {
84                  log.debug("Authentication failed as the received password type does not " 
85                      + "match the required password type of: " + requiredPasswordType);
86              }
87              throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
88          }
89          
90          //
91          // If the UsernameToken is hashed or plaintext, then retrieve the password from the
92          // callback handler and compare directly. If the UsernameToken is of some unknown type,
93          // then delegate authentication to the callback handler
94          //
95          String password = usernameToken.getPassword();
96          if (usernameToken.isHashed()) {
97              verifyDigestPassword(usernameToken, data);
98          } else if (WSConstants.PASSWORD_TEXT.equals(pwType)
99              || (password != null && (pwType == null || "".equals(pwType.trim())))) {
100             verifyPlaintextPassword(usernameToken, data);
101         } else if (password != null) {
102             if (!handleCustomPasswordTypes) {
103                 if (log.isDebugEnabled()) {
104                     log.debug("Authentication failed as handleCustomUsernameTokenTypes is false");
105                 }
106                 throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
107             }
108             verifyCustomPassword(usernameToken, data);
109         } else {
110             verifyUnknownPassword(usernameToken, data);
111         }
112         return credential;
113     }
114     
115     /**
116      * Verify a UsernameToken containing a password of some unknown (but specified) password
117      * type. It does this by querying a CallbackHandler instance to obtain a password for the
118      * given username, and then comparing it against the received password.
119      * This method currently uses the same logic as the verifyPlaintextPassword case, but it in
120      * a separate protected method to allow users to override the validation of the custom 
121      * password type specific case.
122      * @param usernameToken The UsernameToken instance to verify
123      * @throws WSSecurityException on a failed authentication.
124      */
125     protected void verifyCustomPassword(UsernameToken usernameToken,
126                                         RequestData data) throws WSSecurityException {
127         verifyPlaintextPassword(usernameToken, data);
128     }
129     
130     /**
131      * Verify a UsernameToken containing a plaintext password. It does this by querying a 
132      * CallbackHandler instance to obtain a password for the given username, and then comparing
133      * it against the received password.
134      * This method currently uses the same logic as the verifyDigestPassword case, but it in
135      * a separate protected method to allow users to override the validation of the plaintext 
136      * password specific case.
137      * @param usernameToken The UsernameToken instance to verify
138      * @throws WSSecurityException on a failed authentication.
139      */
140     protected void verifyPlaintextPassword(UsernameToken usernameToken,
141                                            RequestData data) throws WSSecurityException {
142         verifyDigestPassword(usernameToken, data);
143     }
144     
145     /**
146      * Verify a UsernameToken containing a password digest. It does this by querying a 
147      * CallbackHandler instance to obtain a password for the given username, and then comparing
148      * it against the received password.
149      * @param usernameToken The UsernameToken instance to verify
150      * @throws WSSecurityException on a failed authentication.
151      */
152     protected void verifyDigestPassword(UsernameToken usernameToken,
153                                         RequestData data) throws WSSecurityException {
154         if (data.getCallbackHandler() == null) {
155             throw new WSSecurityException(WSSecurityException.FAILURE, "noCallback");
156         }
157         
158         String user = usernameToken.getName();
159         String password = usernameToken.getPassword();
160         String nonce = usernameToken.getNonce();
161         String createdTime = usernameToken.getCreated();
162         String pwType = usernameToken.getPasswordType();
163         boolean passwordsAreEncoded = usernameToken.getPasswordsAreEncoded();
164         
165         WSPasswordCallback pwCb = 
166             new WSPasswordCallback(user, null, pwType, WSPasswordCallback.USERNAME_TOKEN, data);
167         try {
168             data.getCallbackHandler().handle(new Callback[]{pwCb});
169         } catch (IOException e) {
170             if (log.isDebugEnabled()) {
171                 log.debug(e);
172             }
173             throw new WSSecurityException(
174                 WSSecurityException.FAILED_AUTHENTICATION, null, null, e
175             );
176         } catch (UnsupportedCallbackException e) {
177             if (log.isDebugEnabled()) {
178                 log.debug(e);
179             }
180             throw new WSSecurityException(
181                 WSSecurityException.FAILED_AUTHENTICATION, null, null, e
182             );
183         }
184         String origPassword = pwCb.getPassword();
185         if (origPassword == null) {
186             if (log.isDebugEnabled()) {
187                 log.debug("Callback supplied no password for: " + user);
188             }
189             throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
190         }
191         if (usernameToken.isHashed()) {
192             String passDigest;
193             if (passwordsAreEncoded) {
194                 passDigest = UsernameToken.doPasswordDigest(nonce, createdTime, Base64.decode(origPassword));
195             } else {
196                 passDigest = UsernameToken.doPasswordDigest(nonce, createdTime, origPassword);
197             }
198             if (!passDigest.equals(password)) {
199                 throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
200             }
201         } else {
202             if (!origPassword.equals(password)) {
203                 throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
204             }
205         }
206     }
207     
208     /**
209      * Verify a UsernameToken containing no password. This does nothing - but is in a separate
210      * method to allow the end-user to override validation easily. 
211      * @param usernameToken The UsernameToken instance to verify
212      * @throws WSSecurityException on a failed authentication.
213      */
214     protected void verifyUnknownPassword(UsernameToken usernameToken,
215                                          RequestData data) throws WSSecurityException {
216         //
217     }
218    
219 }