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.directory.server.ldap.handlers.sasl;
21  
22  
23  import javax.security.sasl.Sasl;
24  import javax.security.sasl.SaslException;
25  import javax.security.sasl.SaslServer;
26  
27  import org.apache.directory.api.ldap.model.constants.SaslQoP;
28  import org.apache.mina.core.buffer.IoBuffer;
29  import org.apache.mina.core.filterchain.IoFilterAdapter;
30  import org.apache.mina.core.session.IoSession;
31  import org.apache.mina.core.write.DefaultWriteRequest;
32  import org.apache.mina.core.write.WriteRequest;
33  import org.slf4j.Logger;
34  import org.slf4j.LoggerFactory;
35  
36  
37  /**
38   * An {@link IoFilterAdapter} that handles integrity and confidentiality protection
39   * for a SASL bound session.  The SaslFilter must be constructed with a SASL
40   * context that has completed SASL negotiation.  Some SASL mechanisms, such as
41   * CRAM-MD5, only support authentication and thus do not need this filter.  DIGEST-MD5
42   * and GSSAPI do support message integrity and confidentiality and, therefore,
43   * do need this filter.
44   * 
45   * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
46   */
47  public class SaslFilter extends IoFilterAdapter
48  {
49      private static final Logger LOG = LoggerFactory.getLogger( SaslFilter.class );
50  
51      /**
52       * A session attribute key that makes next one write request bypass
53       * this filter (not adding a security layer).  This is a marker attribute,
54       * which means that you can put whatever as its value. ({@link Boolean#TRUE}
55       * is preferred.)  The attribute is automatically removed from the session
56       * attribute map as soon as {@link IoSession#write(Object)} is invoked,
57       * and therefore should be put again if you want to make more messages
58       * bypass this filter.
59       */
60      public static final String DISABLE_SECURITY_LAYER_ONCE = SaslFilter.class.getName() + ".DisableSecurityLayerOnce";
61  
62      private SaslServer saslServer;
63  
64  
65      /**
66       * Creates a new instance of SaslFilter.  The SaslFilter must be constructed
67       * with a SASL context that has completed SASL negotiation.  The SASL context
68       * will be used to provide message integrity and, optionally, message
69       * confidentiality.
70       *
71       * @param saslServer The initialized SASL context.
72       */
73      public SaslFilter( SaslServer saslServer )
74      {
75          if ( saslServer == null )
76          {
77              throw new IllegalStateException();
78          }
79  
80          this.saslServer = saslServer;
81      }
82  
83  
84      @Override
85      public void messageReceived( NextFilter nextFilter, IoSession session, Object message ) throws SaslException
86      {
87          LOG.debug( "Message received:  {}", message );
88  
89          /*
90           * Unwrap the data for mechanisms that support QoP (DIGEST-MD5, GSSAPI).
91           */
92          String qop = ( String ) saslServer.getNegotiatedProperty( Sasl.QOP );
93          boolean hasSecurityLayer = ( qop != null && ( qop.equals( SaslQoP.AUTH_INT.getValue() ) || qop
94              .equals( SaslQoP.AUTH_CONF.getValue() ) ) );
95  
96          if ( hasSecurityLayer )
97          {
98              /*
99               * Get the buffer as bytes.  First 4 bytes are length as int.
100              */
101             IoBuffer buf = ( IoBuffer ) message;
102             int bufferLength = buf.getInt();
103             byte[] bufferBytes = new byte[bufferLength];
104             buf.get( bufferBytes );
105 
106             LOG.debug( "Will use SASL to unwrap received message of length:  {}", bufferLength );
107             byte[] token = saslServer.unwrap( bufferBytes, 0, bufferBytes.length );
108             nextFilter.messageReceived( session, IoBuffer.wrap( token ) );
109         }
110         else
111         {
112             LOG.debug( "Will not use SASL on received message." );
113             nextFilter.messageReceived( session, message );
114         }
115     }
116 
117 
118     @Override
119     public void filterWrite( NextFilter nextFilter, IoSession session, WriteRequest writeRequest ) throws SaslException
120     {
121         LOG.debug( "Filtering write request:  {}", writeRequest );
122 
123         /*
124          * Check if security layer processing should be disabled once.
125          */
126         if ( session.containsAttribute( DISABLE_SECURITY_LAYER_ONCE ) )
127         {
128             // Remove the marker attribute because it is temporary.
129             LOG.debug( "Disabling SaslFilter once; will not use SASL on write request." );
130             session.removeAttribute( DISABLE_SECURITY_LAYER_ONCE );
131             nextFilter.filterWrite( session, writeRequest );
132             return;
133         }
134 
135         /*
136          * Wrap the data for mechanisms that support QoP (DIGEST-MD5, GSSAPI).
137          */
138         String qop = ( String ) saslServer.getNegotiatedProperty( Sasl.QOP );
139         boolean hasSecurityLayer = ( qop != null && ( qop.equals( SaslQoP.AUTH_INT.getValue() ) || qop
140             .equals( SaslQoP.AUTH_CONF.getValue() ) ) );
141 
142         IoBuffer saslLayerBuffer = null;
143 
144         if ( hasSecurityLayer )
145         {
146             /*
147              * Get the buffer as bytes.
148              */
149             IoBuffer buf = ( IoBuffer ) writeRequest.getMessage();
150             int bufferLength = buf.remaining();
151             byte[] bufferBytes = new byte[bufferLength];
152             buf.get( bufferBytes );
153 
154             LOG.debug( "Will use SASL to wrap message of length:  {}", bufferLength );
155 
156             byte[] saslLayer = saslServer.wrap( bufferBytes, 0, bufferBytes.length );
157 
158             /*
159              * Prepend 4 byte length.
160              */
161             saslLayerBuffer = IoBuffer.allocate( 4 + saslLayer.length );
162             saslLayerBuffer.putInt( saslLayer.length );
163             saslLayerBuffer.put( saslLayer );
164             saslLayerBuffer.position( 0 );
165             saslLayerBuffer.limit( 4 + saslLayer.length );
166 
167             LOG.debug( "Sending encrypted token of length {}.", saslLayerBuffer.limit() );
168             nextFilter.filterWrite( session, new DefaultWriteRequest( saslLayerBuffer, writeRequest.getFuture() ) );
169         }
170         else
171         {
172             LOG.debug( "Will not use SASL on write request." );
173             nextFilter.filterWrite( session, writeRequest );
174         }
175     }
176 }