Save This Page
Home » wss4j-src-1.5.7 » org.apache.ws.security » [javadoc | source]
    1   /*
    2    * Copyright  2003-2005 The Apache Software Foundation.
    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   
   18   package org.apache.ws.security;
   19   
   20   import java.util.HashMap;
   21   
   22   import javax.xml.namespace.QName;
   23   
   24   import org.apache.commons.logging.Log;
   25   import org.apache.commons.logging.LogFactory;
   26   import org.apache.ws.security.action.Action;
   27   import org.apache.ws.security.processor.Processor;
   28   import org.apache.ws.security.transform.STRTransform;
   29   import org.apache.ws.security.util.Loader;
   30   import org.apache.ws.security.util.UUIDGenerator;
   31   import org.apache.xml.security.transforms.Transform;
   32   
   33   /**
   34    * WSSConfig <p/> Carries configuration data so the WSS4J spec compliance can be
   35    * modified in runtime. Configure an instance of this object only if you need
   36    * WSS4J to emulate certain industry clients or previous OASIS specifications
   37    * for WS-Security interoperability testing purposes. <p/> The default settings
   38    * follow the latest OASIS and changing anything might violate the OASIS specs.
   39    * <p/> <b>WARNING: changing the default settings will break the compliance with
   40    * the latest specs. Do this only if you know what you are doing.</b> <p/>
   41    * 
   42    * @author Rami Jaamour (rjaamour@parasoft.com)
   43    * @author Werner Dittmann (werner@apache.org)
   44    */
   45   public class WSSConfig {
   46       
   47       private static final Log log = LogFactory.getLog(WSSConfig.class.getName());
   48   
   49       /**
   50        * The default collection of actions supported by the toolkit.
   51        */
   52       private static final java.util.Map DEFAULT_ACTIONS;
   53       static {
   54           final java.util.Map tmp = new java.util.HashMap();
   55           try {
   56               tmp.put(
   57                   new Integer(WSConstants.UT),
   58                   org.apache.ws.security.action.UsernameTokenAction.class.getName()
   59               );
   60               tmp.put(
   61                   new Integer(WSConstants.ENCR),
   62                   org.apache.ws.security.action.EncryptionAction.class.getName()
   63               );
   64               tmp.put(
   65                   new Integer(WSConstants.SIGN),
   66                   org.apache.ws.security.action.SignatureAction.class.getName()
   67               );
   68               //
   69               // Note that all actions/processors with dependencies on opensaml are
   70               // registered as Strings. This is so that applications that do not use
   71               // saml do not have to have the opensaml jar available.
   72               //
   73               tmp.put(
   74                   new Integer(WSConstants.ST_SIGNED),
   75                   "org.apache.ws.security.action.SAMLTokenSignedAction"
   76               );
   77               tmp.put(
   78                   new Integer(WSConstants.ST_UNSIGNED),
   79                   "org.apache.ws.security.action.SAMLTokenUnsignedAction"
   80               );
   81               tmp.put(
   82                   new Integer(WSConstants.TS),
   83                   org.apache.ws.security.action.TimestampAction.class.getName()
   84               );
   85               tmp.put(
   86                   new Integer(WSConstants.UT_SIGN),
   87                   org.apache.ws.security.action.UsernameTokenSignedAction.class.getName()
   88               );
   89               tmp.put(
   90                   new Integer(WSConstants.SC),
   91                   org.apache.ws.security.action.SignatureConfirmationAction.class.getName()
   92               );
   93           } catch (final Throwable t) {
   94               if (log.isDebugEnabled()) {
   95                   log.debug(t.getMessage(), t);
   96               }
   97           }
   98           DEFAULT_ACTIONS = java.util.Collections.unmodifiableMap(tmp);
   99       }
  100   
  101       /**
  102        * The default collection of processors supported by the toolkit
  103        */
  104       private static final java.util.Map DEFAULT_PROCESSORS;
  105       static {
  106           final java.util.Map tmp = new java.util.HashMap();
  107           try {
  108               tmp.put(
  109                   WSSecurityEngine.SAML_TOKEN,
  110                   "org.apache.ws.security.processor.SAMLTokenProcessor"
  111               );
  112               tmp.put(
  113                   WSSecurityEngine.ENCRYPTED_KEY,
  114                   org.apache.ws.security.processor.EncryptedKeyProcessor.class.getName()
  115               );
  116               tmp.put(
  117                   WSSecurityEngine.SIGNATURE,
  118                   org.apache.ws.security.processor.SignatureProcessor.class.getName()
  119               );
  120               tmp.put(
  121                   WSSecurityEngine.timeStamp,
  122                   org.apache.ws.security.processor.TimestampProcessor.class.getName()
  123               );
  124               tmp.put(
  125                   WSSecurityEngine.usernameToken,
  126                   org.apache.ws.security.processor.UsernameTokenProcessor.class.getName()
  127               );
  128               tmp.put(
  129                   WSSecurityEngine.REFERENCE_LIST,
  130                   org.apache.ws.security.processor.ReferenceListProcessor.class.getName()
  131               );
  132               tmp.put(
  133                   WSSecurityEngine.signatureConfirmation,
  134                   org.apache.ws.security.processor.SignatureConfirmationProcessor.class.getName()
  135               );
  136               tmp.put(
  137                   WSSecurityEngine.DERIVED_KEY_TOKEN_05_02,
  138                   org.apache.ws.security.processor.DerivedKeyTokenProcessor.class.getName()
  139               );
  140               tmp.put(
  141                   WSSecurityEngine.DERIVED_KEY_TOKEN_05_12,
  142                   tmp.get(WSSecurityEngine.DERIVED_KEY_TOKEN_05_02)
  143               );
  144               tmp.put(
  145                   WSSecurityEngine.SECURITY_CONTEXT_TOKEN_05_02,
  146                   org.apache.ws.security.processor.SecurityContextTokenProcessor.class.getName()
  147               );
  148               tmp.put(
  149                   WSSecurityEngine.SECURITY_CONTEXT_TOKEN_05_12,
  150                   tmp.get(WSSecurityEngine.SECURITY_CONTEXT_TOKEN_05_02)
  151               );
  152               tmp.put(
  153                   WSSecurityEngine.binaryToken,
  154                   org.apache.ws.security.processor.BinarySecurityTokenProcessor.class.getName()
  155               );
  156               tmp.put(
  157                   WSSecurityEngine.ENCRYPTED_DATA,
  158                   org.apache.ws.security.processor.EncryptedDataProcessor.class.getName()
  159               );
  160           } catch (final Throwable t) {
  161               if (log.isDebugEnabled()) {
  162                   log.debug(t.getMessage(), t);
  163               }
  164           }
  165           DEFAULT_PROCESSORS = java.util.Collections.unmodifiableMap(tmp);
  166       }
  167   
  168       protected static WSSConfig defaultConfig = null;
  169   
  170       protected boolean wsiBSPCompliant = false;
  171   
  172       /**
  173        * Set the timestamp precision mode. If set to <code>true</code> then use
  174        * timestamps with milliseconds, otherwise omit the milliseconds. As per XML
  175        * Date/Time specification the default is to include the milliseconds.
  176        */
  177       protected boolean precisionInMilliSeconds = true;
  178   
  179       protected boolean enableSignatureConfirmation = true;
  180   
  181       /**
  182        * If set to true then the timestamp handling will throw an exception if the
  183        * timestamp contains an expires element and the semantics are expired.
  184        * 
  185        * If set to false, no exception will be thrown, even if the semantics are
  186        * expired.
  187        */
  188       protected boolean timeStampStrict = true;
  189       
  190       /**
  191        * This variable controls whether types other than PasswordDigest or PasswordText
  192        * are allowed when processing UsernameTokens. 
  193        * 
  194        * By default this is set to false so that the user doesn't have to explicitly
  195        * reject custom token types in the callback handler.
  196        */
  197       protected boolean handleCustomPasswordTypes = false;
  198       
  199       
  200       /**
  201        * The default wsu:Id allocator is a simple "start at 1 and increment up"
  202        * thing that is very fast.
  203        */
  204       public static WsuIdAllocator DEFAULT_ID_ALLOCATOR = new WsuIdAllocator() {
  205           int i;
  206           private synchronized String next() {
  207               return Integer.toString(++i);
  208           }
  209           public String createId(String prefix, Object o) {
  210               if (prefix == null) {
  211                   return next();
  212               }
  213               return prefix + next();
  214           }
  215   
  216           public String createSecureId(String prefix, Object o) {
  217               if (prefix == null) {
  218                   return UUIDGenerator.getUUID();
  219               }
  220               return prefix + UUIDGenerator.getUUID();
  221           }
  222       };
  223       protected WsuIdAllocator idAllocator = DEFAULT_ID_ALLOCATOR;
  224       
  225       protected HashMap jceProvider = new HashMap(10);
  226   
  227       /**
  228        * The known actions. This map is of the form <Integer, String> or <Integer, Action>. 
  229        * The known actions are initialized from a set of defaults,
  230        * but the list may be modified via the setAction operations.
  231        */
  232       private final java.util.Map actionMap = new java.util.HashMap(DEFAULT_ACTIONS);
  233   
  234       /**
  235        * The known processors. This map is of the form <String, String> or <String,Processor>.
  236        * The known processors are initialized from a set of defaults,
  237        * but the list may be modified via the setProcessor operations.
  238        */
  239       private final java.util.Map processorMap = new java.util.HashMap(DEFAULT_PROCESSORS);
  240       
  241       /**
  242        * a static boolean flag that determines whether default JCE providers
  243        * should be added at the time of construction.
  244        *
  245        * These providers, and the order in which they are added, can interfere
  246        * with some JVMs (such as IBMs).
  247        */
  248       private static boolean addJceProviders = true;
  249       
  250       /**
  251        * a boolean flag to record whether we have already been statically
  252        * initialized.  This flag prevents repeated and unnecessary calls
  253        * to static initialization code at construction time.
  254        */
  255       private static boolean staticallyInitialized = false;
  256       
  257       /**
  258        * Set the value of the internal addJceProviders flag.  This flag
  259        * turns on (or off) automatic registration of known JCE providers
  260        * that provide necessary cryptographic algorithms for use with WSS4J.
  261        * By default, this flag is true, for backwards compatibility.  You may
  262        * wish (or need) to initialize the JCE manually, e.g., in some JVMs.
  263        */
  264       public static void setAddJceProviders(boolean value) {
  265           addJceProviders = value;
  266       }
  267       
  268       private synchronized void
  269       staticInit() {
  270           if (!staticallyInitialized) {
  271               org.apache.xml.security.Init.init();
  272               if (addJceProviders) {
  273                   /*
  274                    * The last provider added has precedence, that is if JuiCE can be added
  275                    * then WSS4J uses this provider.
  276                    */
  277                   addJceProvider("BC", "org.bouncycastle.jce.provider.BouncyCastleProvider");
  278                   addJceProvider("JuiCE", "org.apache.security.juice.provider.JuiCEProviderOpenSSL");
  279               }
  280               Transform.init();
  281               try {
  282                   Transform.register(
  283                       STRTransform.implementedTransformURI,
  284                       "org.apache.ws.security.transform.STRTransform"
  285                   );
  286               } catch (Exception ex) {
  287                   if (log.isDebugEnabled()) {
  288                       log.debug(ex.getMessage(), ex);
  289                   }
  290               }
  291               staticallyInitialized = true;
  292           }
  293       }
  294       
  295       protected WSSConfig() {
  296           staticInit();
  297       }
  298       
  299       /**
  300        * @return a new WSSConfig instance configured with the default values
  301        *         (values identical to
  302        *         {@link #getDefaultWSConfig getDefaultWSConfig()})
  303        */
  304       public static WSSConfig getNewInstance() {
  305           return new WSSConfig();
  306       }
  307   
  308       /**
  309        * returns a static WSConfig instance that is configured with the latest
  310        * OASIS WS-Security settings.
  311        */
  312       public static WSSConfig getDefaultWSConfig() {
  313           if (defaultConfig == null) {
  314               defaultConfig = getNewInstance();
  315           }
  316           return defaultConfig;
  317       }
  318       
  319       /**
  320        * Checks if we are in WS-I Basic Security Profile compliance mode
  321        * 
  322        * @return TODO
  323        */
  324       public boolean isWsiBSPCompliant() {
  325           return wsiBSPCompliant;
  326       }
  327   
  328       /**
  329        * Set the WS-I Basic Security Profile compliance mode. The default is false
  330        * (dues to .Net interop problems).
  331        * 
  332        * @param wsiBSPCompliant
  333        */
  334       public void setWsiBSPCompliant(boolean wsiBSPCompliant) {
  335           this.wsiBSPCompliant = wsiBSPCompliant;
  336       }
  337   
  338       /**
  339        * Checks if we need to use milliseconds in timestamps
  340        * 
  341        * @return TODO
  342        */
  343       public boolean isPrecisionInMilliSeconds() {
  344           return precisionInMilliSeconds;
  345       }
  346   
  347       /**
  348        * Set the precision in milliseconds
  349        * 
  350        * @param precisionInMilliSeconds
  351        *            TODO
  352        */
  353       public void setPrecisionInMilliSeconds(boolean precisionInMilliSeconds) {
  354           this.precisionInMilliSeconds = precisionInMilliSeconds;
  355       }
  356   
  357       /**
  358        * @return Returns the enableSignatureConfirmation.
  359        */
  360       public boolean isEnableSignatureConfirmation() {
  361           return enableSignatureConfirmation;
  362       }
  363   
  364       /**
  365        * @param enableSignatureConfirmation
  366        *            The enableSignatureConfirmation to set.
  367        */
  368       public void setEnableSignatureConfirmation(boolean enableSignatureConfirmation) {
  369           this.enableSignatureConfirmation = enableSignatureConfirmation;
  370       }
  371       
  372       /**
  373        * @param handleCustomTypes 
  374        * whether to handle custom UsernameToken password types or not
  375        */
  376       public void setHandleCustomPasswordTypes(boolean handleCustomTypes) {
  377           this.handleCustomPasswordTypes = handleCustomTypes;
  378       }
  379       
  380       /**
  381        * @return whether custom UsernameToken password types are allowed or not
  382        */
  383       public boolean getHandleCustomPasswordTypes() {
  384           return handleCustomPasswordTypes;
  385       }
  386   
  387       /**
  388        * @return Returns if we shall throw an exception on expired request
  389        *         semantic
  390        */
  391       public boolean isTimeStampStrict() {
  392           return timeStampStrict;
  393       }
  394   
  395       /**
  396        * @param timeStampStrict
  397        *            If true throw an exception on expired request semantic
  398        */
  399       public void setTimeStampStrict(boolean timeStampStrict) {
  400           this.timeStampStrict = timeStampStrict;
  401       }
  402       
  403       /**
  404        * @return Returns the WsuIdAllocator used to generate wsu:Id attributes
  405        */
  406       public WsuIdAllocator getIdAllocator() {
  407           return idAllocator;
  408       }
  409   
  410       public void setIdAllocator(WsuIdAllocator idAllocator) {
  411           this.idAllocator = idAllocator;
  412       }
  413   
  414       /**
  415        * Associate an action name with a specific action code.
  416        *
  417        * This operation allows applications to supply their own
  418        * actions for well-known operations.
  419        */
  420       public String setAction(int code, String action) {
  421           Object previousAction = actionMap.put(new Integer(code), action);
  422           if (previousAction instanceof String) {
  423               return (String)previousAction;
  424           } else if (previousAction instanceof Action){
  425               return previousAction.getClass().getName();
  426           }
  427           return null;
  428       }
  429       
  430       /**
  431        * Associate an action instance with a specific action code.
  432        *
  433        * This operation allows applications to supply their own
  434        * actions for well-known operations.
  435        */
  436       public String setAction(int code, Action action) {
  437           Object previousAction = actionMap.put(new Integer(code), action);
  438           if (previousAction instanceof String) {
  439               return (String)previousAction;
  440           } else if (previousAction instanceof Action){
  441               return previousAction.getClass().getName();
  442           }
  443           return null;
  444       }
  445   
  446       /**
  447        * Lookup action
  448        * 
  449        * @param action
  450        * @return An action class to create a security token
  451        * @throws WSSecurityException
  452        */
  453       public Action getAction(int action) throws WSSecurityException {
  454           Integer key = new Integer(action);
  455           final Object actionObject = actionMap.get(key);
  456           
  457           if (actionObject instanceof String) {
  458               final String name = (String)actionObject;
  459               try {
  460                   return (Action) Loader.loadClass(name).newInstance();
  461               } catch (Throwable t) {
  462                   if (log.isDebugEnabled()) {
  463                       log.debug(t.getMessage(), t);
  464                   }
  465                   throw new WSSecurityException(WSSecurityException.FAILURE,
  466                           "unableToLoadClass", new Object[] { name }, t);
  467               }
  468           } else if (actionObject instanceof Action) {
  469               return (Action)actionObject;
  470           } 
  471           return null;
  472       }
  473       
  474       /**
  475        * Associate a SOAP processor name with a specified SOAP Security header
  476        * element QName.  Processors registered under this QName will be
  477        * called when processing header elements with the specified type.
  478        */
  479       public String setProcessor(QName el, String name) {
  480           Object previousProcessor = processorMap.put(el, name);
  481           if (previousProcessor instanceof String) {
  482               return (String)previousProcessor;
  483           } else if (previousProcessor instanceof Processor){
  484               return previousProcessor.getClass().getName();
  485           }
  486           return null;
  487       }
  488       
  489       /**
  490        * Associate a SOAP processor instance with a specified SOAP Security header
  491        * element QName.  Processors registered under this QName will be
  492        * called when processing header elements with the specified type.
  493        */
  494       public String setProcessor(QName el, Processor processor) {
  495           Object previousProcessor = processorMap.put(el, processor);
  496           if (previousProcessor instanceof String) {
  497               return (String)previousProcessor;
  498           } else if (previousProcessor instanceof Processor){
  499               return previousProcessor.getClass().getName();
  500           }
  501           return null;
  502       }
  503   
  504       /**
  505        * @return      the SOAP processor associated with the specified
  506        *              QName.  The QName is intended to refer to an element
  507        *              in a SOAP security header.  This operation returns
  508        *              null if there is no processor associated with the 
  509        *              specified QName.
  510        */
  511       public Processor getProcessor(QName el) throws WSSecurityException {
  512           final Object processorObject = processorMap.get(el);
  513           if (processorObject instanceof String) {
  514               final String name = (String)processorObject;
  515               try {
  516                   return (Processor) Loader.loadClass(name).newInstance();
  517               } catch (Throwable t) {
  518                   if (log.isDebugEnabled()) {
  519                       log.debug(t.getMessage(), t);
  520                   }
  521                   throw new WSSecurityException(WSSecurityException.FAILURE,
  522                           "unableToLoadClass", new Object[] { name }, t);
  523               }
  524           } else if (processorObject instanceof Processor) {
  525               return (Processor)processorObject;
  526           } 
  527           return null;
  528       }
  529   
  530       private boolean loadProvider(String id, String className) {
  531           try {
  532               if (java.security.Security.getProvider(id) == null) {
  533                   Class c = Loader.loadClass(className, false);
  534                   java.security.Provider[] provs = 
  535                       java.security.Security.getProviders();
  536                   //
  537                   // Install the provider after the SUN provider (see WSS-99)
  538                   // Otherwise fall back to the old behaviour of inserting
  539                   // the provider in position 2. For AIX, install it after
  540                   // the IBMJCE provider.
  541                   //
  542                   int ret = 0;
  543                   for (int i = 0; i < provs.length; i++) {
  544                       if ("SUN".equals(provs[i].getName())
  545                           || "IBMJCE".equals(provs[i].getName())) {
  546                           ret =
  547                               java.security.Security.insertProviderAt(
  548                                   (java.security.Provider) c.newInstance(), i + 2
  549                               );
  550                           break;
  551                       }
  552                   }
  553                   if (ret == 0) {
  554                       ret =
  555                       java.security.Security.insertProviderAt(
  556                           (java.security.Provider) c.newInstance(), 2
  557                       );
  558                   }
  559                   if (log.isDebugEnabled()) {
  560                       log.debug("The provider " + id + " was added at position: " + ret);
  561                   }                
  562               }
  563               return true;
  564           } catch (Throwable t) {
  565               if (log.isDebugEnabled()) {
  566                   log.debug("The provider " + id + " could not be added: " + t.getMessage());
  567               }
  568               return false;
  569           }
  570   
  571       }
  572   
  573       /**
  574        * Add a new JCE security provider to use for WSS4J.
  575        * 
  576        * If the provider is not already known the method loads a security provider
  577        * class and adds the provider to the java security service.
  578        * 
  579        * 
  580        * @param id
  581        *            The id string of the provider
  582        * @param className
  583        *            Name of the class the implements the provider. This class must
  584        *            be a subclass of <code>java.security.Provider</code>
  585        * 
  586        * @return Returns <code>true</code> if the provider was successfully
  587        *         added, <code>false</code> otherwise.
  588        */
  589       public boolean addJceProvider(String id, String className) {
  590           if (jceProvider.get(id) == null && loadProvider(id, className)) {
  591               jceProvider.put(id, className);
  592               return true;
  593           }
  594           return false;
  595       }
  596   }

Save This Page
Home » wss4j-src-1.5.7 » org.apache.ws.security » [javadoc | source]