<commit_before>/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *  
 *    http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License. 
 *  
 */
package org.apache.directory.server.kerberos;


import org.apache.directory.server.core.DefaultDirectoryService;
import org.apache.directory.server.core.DirectoryService;
import org.apache.directory.server.core.entry.ServerEntry;
import org.apache.directory.server.core.integ.IntegrationUtils;
import org.apache.directory.server.core.integ.Level;
import org.apache.directory.server.core.integ.annotations.ApplyLdifs;
import org.apache.directory.server.core.integ.annotations.CleanupLevel;
import org.apache.directory.server.core.integ.annotations.Factory;
import org.apache.directory.server.core.interceptor.Interceptor;
import org.apache.directory.server.core.kerberos.KeyDerivationInterceptor;
import org.apache.directory.server.core.partition.Partition;
import org.apache.directory.server.xdbm.Index;
import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmIndex;
import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmPartition;
import org.apache.directory.server.integ.LdapServerFactory;
import static org.apache.directory.server.integ.ServerIntegrationUtils.getWiredContext;
import org.apache.directory.server.integ.SiRunner;
import org.apache.directory.server.kerberos.shared.crypto.encryption.EncryptionType;
import org.apache.directory.server.kerberos.shared.io.decoder.EncryptionKeyDecoder;
import org.apache.directory.server.kerberos.shared.messages.value.EncryptionKey;
import org.apache.directory.server.kerberos.shared.store.KerberosAttribute;
import org.apache.directory.server.ldap.LdapServer;
import org.apache.directory.server.ldap.handlers.bind.MechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.cramMD5.CramMd5MechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.digestMD5.DigestMd5MechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.gssapi.GssapiMechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.ntlm.NtlmMechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.plain.PlainMechanismHandler;
import org.apache.directory.server.ldap.handlers.extended.StoredProcedureExtendedOperationHandler;
import org.apache.directory.server.protocol.shared.transport.TcpTransport;
import org.apache.directory.shared.ldap.constants.SupportedSaslMechanisms;
import org.apache.mina.util.AvailablePortFinder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import javax.crypto.spec.DESKeySpec;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * An test case for testing the {@link KeyDerivationInterceptor}'s
 * ability to derive Kerberos symmetric keys based on userPassword and principal
 * name and to generate random keys when the special keyword "randomKey" is used.
 * 
 * @author <a href="mailto:<EMAIL>">Apache Directory Project</a>
 * @version $Rev$, $Date$
 */
@RunWith ( SiRunner.class ) 
@CleanupLevel ( Level.CLASS )
@Factory ( KeyDerivationServiceIT.Factory.class )
@ApplyLdifs( {
    // Entry #0
    "dn: dc=example,dc=com\n" +
    "dc: example\n" +
    "objectClass: top\n" +
    "objectClass: domain\n\n"
    }
)
public class KeyDerivationServiceIT 
{
    private static final String RDN = "uid=hnelson,ou=users,dc=example,dc=com";


    public static LdapServer ldapServer;

     
     public static class Factory implements LdapServerFactory
     {
         public LdapServer newInstance() throws Exception
         {
             DirectoryService service = new DefaultDirectoryService();
             IntegrationUtils.doDelete( service.getWorkingDirectory() );
             service.getChangeLog().setEnabled( true );
             service.setAllowAnonymousAccess( false );
             service.setShutdownHookEnabled( false );

             Set<Partition> partitions = new HashSet<Partition>();
             JdbmPartition partition = new JdbmPartition();
             partition.setId( "example" );
             partition.setSuffix( "dc=example,dc=com" );

             Set<Index<?,ServerEntry>> indexedAttrs = new HashSet<Index<?,ServerEntry>>();
             indexedAttrs.add( new JdbmIndex<String,ServerEntry>( "ou" ) );
             indexedAttrs.add( new JdbmIndex<String,ServerEntry>( "dc" ) );
             indexedAttrs.add( new JdbmIndex<String,ServerEntry>( "objectClass" ) );
             partition.setIndexedAttributes( indexedAttrs );

             partitions.add( partition );
             service.setPartitions( partitions );

             List<Interceptor> list = service.getInterceptors();
             list.add( new KeyDerivationInterceptor() );
             service.setInterceptors( list );
             
             // change the working directory to something that is unique
             // on the system and somewhere either under target directory
             // or somewhere in a temp area of the machine.

             LdapServer ldapServer = new LdapServer();
             ldapServer.setDirectoryService( service );
             int port = AvailablePortFinder.getNextAvailable( 1024 );
             ldapServer.setTransports( new TcpTransport( port ) );
             ldapServer.setAllowAnonymousAccess( false );
             ldapServer.addExtendedOperationHandler( new StoredProcedureExtendedOperationHandler() );

             // Setup SASL Mechanisms
             
             Map<String, MechanismHandler> mechanismHandlerMap = new HashMap<String,MechanismHandler>();
             mechanismHandlerMap.put( SupportedSaslMechanisms.PLAIN, new PlainMechanismHandler() );

             CramMd5MechanismHandler cramMd5MechanismHandler = new CramMd5MechanismHandler();
             mechanismHandlerMap.put( SupportedSaslMechanisms.CRAM_MD5, cramMd5MechanismHandler );

             DigestMd5MechanismHandler digestMd5MechanismHandler = new DigestMd5MechanismHandler();
             mechanismHandlerMap.put( SupportedSaslMechanisms.DIGEST_MD5, digestMd5MechanismHandler );

             GssapiMechanismHandler gssapiMechanismHandler = new GssapiMechanismHandler();
             mechanismHandlerMap.put( SupportedSaslMechanisms.GSSAPI, gssapiMechanismHandler );

             NtlmMechanismHandler ntlmMechanismHandler = new NtlmMechanismHandler();
             mechanismHandlerMap.put( SupportedSaslMechanisms.NTLM, ntlmMechanismHandler );
             mechanismHandlerMap.put( SupportedSaslMechanisms.GSS_SPNEGO, ntlmMechanismHandler );

             ldapServer.setSaslMechanismHandlers( mechanismHandlerMap );
             ldapServer.setSaslHost( "localhost" );
             
             return ldapServer;
         }
     }
     
     
     private void checkKeyNumber( Attributes attributes )
     {
         Attribute krb5key = attributes.get( "krb5key" );
         
         String vendor = System.getProperty( "java.vm.vendor" );
         
         if ( vendor.equalsIgnoreCase( "IBM Corporation") )
         {
             // Will be 2 or 3 on IBM JRE whether AES-256 is enabled or not
             assertTrue( "Number of keys", krb5key.size() > 1 );
         }
         else if ( vendor.equalsIgnoreCase( "Sun Microsystems Inc." ) )
         {
             // Could be 4 or 5 depending on whether AES-256 is enabled or not, on SUN JRE
             assertTrue( "Number of keys", krb5key.size() > 3 );
         }
         else if ( vendor.equalsIgnoreCase( "BEA Systems, Inc." ) )
         {
             // Could be 4 or 5 depending on whether AES-256 is enabled or not, on JRockit
             assertTrue( "Number of keys", krb5key.size() > 3 );
         }
         else
         {
             fail( "Unkown JVM" );
         }
     }
     
     
    /**
     * Set up a partition for EXAMPLE.COM, add the Key Derivation interceptor, enable<commit_msg>Fixed the build on Mac OS X. Added the needed information on Mac OS X JVM.<commit_after>/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *  
 *    http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License. 
 *  
 */
package org.apache.directory.server.kerberos;


import org.apache.directory.server.core.DefaultDirectoryService;
import org.apache.directory.server.core.DirectoryService;
import org.apache.directory.server.core.entry.ServerEntry;
import org.apache.directory.server.core.integ.IntegrationUtils;
import org.apache.directory.server.core.integ.Level;
import org.apache.directory.server.core.integ.annotations.ApplyLdifs;
import org.apache.directory.server.core.integ.annotations.CleanupLevel;
import org.apache.directory.server.core.integ.annotations.Factory;
import org.apache.directory.server.core.interceptor.Interceptor;
import org.apache.directory.server.core.kerberos.KeyDerivationInterceptor;
import org.apache.directory.server.core.partition.Partition;
import org.apache.directory.server.xdbm.Index;
import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmIndex;
import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmPartition;
import org.apache.directory.server.integ.LdapServerFactory;
import static org.apache.directory.server.integ.ServerIntegrationUtils.getWiredContext;
import org.apache.directory.server.integ.SiRunner;
import org.apache.directory.server.kerberos.shared.crypto.encryption.EncryptionType;
import org.apache.directory.server.kerberos.shared.io.decoder.EncryptionKeyDecoder;
import org.apache.directory.server.kerberos.shared.messages.value.EncryptionKey;
import org.apache.directory.server.kerberos.shared.store.KerberosAttribute;
import org.apache.directory.server.ldap.LdapServer;
import org.apache.directory.server.ldap.handlers.bind.MechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.cramMD5.CramMd5MechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.digestMD5.DigestMd5MechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.gssapi.GssapiMechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.ntlm.NtlmMechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.plain.PlainMechanismHandler;
import org.apache.directory.server.ldap.handlers.extended.StoredProcedureExtendedOperationHandler;
import org.apache.directory.server.protocol.shared.transport.TcpTransport;
import org.apache.directory.shared.ldap.constants.SupportedSaslMechanisms;
import org.apache.mina.util.AvailablePortFinder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import javax.crypto.spec.DESKeySpec;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * An test case for testing the {@link KeyDerivationInterceptor}'s
 * ability to derive Kerberos symmetric keys based on userPassword and principal
 * name and to generate random keys when the special keyword "randomKey" is used.
 * 
 * @author <a href="mailto:<EMAIL>">Apache Directory Project</a>
 * @version $Rev$, $Date$
 */
@RunWith ( SiRunner.class ) 
@CleanupLevel ( Level.CLASS )
@Factory ( KeyDerivationServiceIT.Factory.class )
@ApplyLdifs( {
    // Entry #0
    "dn: dc=example,dc=com\n" +
    "dc: example\n" +
    "objectClass: top\n" +
    "objectClass: domain\n\n"
    }
)
public class KeyDerivationServiceIT 
{
    private static final String RDN = "uid=hnelson,ou=users,dc=example,dc=com";


    public static LdapServer ldapServer;

     
     public static class Factory implements LdapServerFactory
     {
         public LdapServer newInstance() throws Exception
         {
             DirectoryService service = new DefaultDirectoryService();
             IntegrationUtils.doDelete( service.getWorkingDirectory() );
             service.getChangeLog().setEnabled( true );
             service.setAllowAnonymousAccess( false );
             service.setShutdownHookEnabled( false );

             Set<Partition> partitions = new HashSet<Partition>();
             JdbmPartition partition = new JdbmPartition();
             partition.setId( "example" );
             partition.setSuffix( "dc=example,dc=com" );

             Set<Index<?,ServerEntry>> indexedAttrs = new HashSet<Index<?,ServerEntry>>();
             indexedAttrs.add( new JdbmIndex<String,ServerEntry>( "ou" ) );
             indexedAttrs.add( new JdbmIndex<String,ServerEntry>( "dc" ) );
             indexedAttrs.add( new JdbmIndex<String,ServerEntry>( "objectClass" ) );
             partition.setIndexedAttributes( indexedAttrs );

             partitions.add( partition );
             service.setPartitions( partitions );

             List<Interceptor> list = service.getInterceptors();
             list.add( new KeyDerivationInterceptor() );
             service.setInterceptors( list );
             
             // change the working directory to something that is unique
             // on the system and somewhere either under target directory
             // or somewhere in a temp area of the machine.

             LdapServer ldapServer = new LdapServer();
             ldapServer.setDirectoryService( service );
             int port = AvailablePortFinder.getNextAvailable( 1024 );
             ldapServer.setTransports( new TcpTransport( port ) );
             ldapServer.setAllowAnonymousAccess( false );
             ldapServer.addExtendedOperationHandler( new StoredProcedureExtendedOperationHandler() );

             // Setup SASL Mechanisms
             
             Map<String, MechanismHandler> mechanismHandlerMap = new HashMap<String,MechanismHandler>();
             mechanismHandlerMap.put( SupportedSaslMechanisms.PLAIN, new PlainMechanismHandler() );

             CramMd5MechanismHandler cramMd5MechanismHandler = new CramMd5MechanismHandler();
             mechanismHandlerMap.put( SupportedSaslMechanisms.CRAM_MD5, cramMd5MechanismHandler );

             DigestMd5MechanismHandler digestMd5MechanismHandler = new DigestMd5MechanismHandler();
             mechanismHandlerMap.put( SupportedSaslMechanisms.DIGEST_MD5, digestMd5MechanismHandler );

             GssapiMechanismHandler gssapiMechanismHandler = new GssapiMechanismHandler();
             mechanismHandlerMap.put( SupportedSaslMechanisms.GSSAPI, gssapiMechanismHandler );

             NtlmMechanismHandler ntlmMechanismHandler = new NtlmMechanismHandler();
             mechanismHandlerMap.put( SupportedSaslMechanisms.NTLM, ntlmMechanismHandler );
             mechanismHandlerMap.put( SupportedSaslMechanisms.GSS_SPNEGO, ntlmMechanismHandler );

             ldapServer.setSaslMechanismHandlers( mechanismHandlerMap );
             ldapServer.setSaslHost( "localhost" );
             
             return ldapServer;
         }
     }
     
     
     private void checkKeyNumber( Attributes attributes )
     {
         Attribute krb5key = attributes.get( "krb5key" );
         
         String vendor = System.getProperty( "java.vm.vendor" );
         
         if ( vendor.equalsIgnoreCase( "IBM Corporation") )
         {
             // Will be 2 or 3 on IBM JRE whether AES-256 is enabled or not
             assertTrue( "Number of keys", krb5key.size() > 1 );
         }
         else if ( vendor.equalsIgnoreCase( "Sun Microsystems Inc." ) )
         {
             // Could be 4 or 5 depending on whether AES-256 is enabled or not, on SUN JRE
             assertTrue( "Number of keys", krb5key.size() > 3 );
         }
         else if ( vendor.equalsIgnoreCase( "BEA Systems, Inc." ) )
         {
             // Could be 4 or 5 depending on whether AES-256 is enabled or not, on JRockit
             assertTrue( "Number of keys", krb5key.size() > 3 );
         }
         else if ( vendor.equalsIgnoreCase( "Apple Inc." ) )
         {
             // Could be 4 or 5 depending on whether AES-256 is enabled or not, on Apple JVM
             assertTrue( "Number of keys", krb5key.size() > 3 );
         }
         else
         {
             fail( "Unkown JVM" );
         }
     }
     
     
    /**
     * Set up a partition for EXAMPLE.COM, add the Key Derivation interceptor, enable
{'fraction_non_alphanumeric': 0.09075451647183846, 'fraction_numerical': 0.005260361317747078, 'mean_word_length': 3.3207070707070705, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 40, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4337379', 'n_tokens_mistral': 5409, 'n_tokens_neox': 5315, 'n_words': 1189}