Java Examples for javax.security.auth.login.Configuration

The following java examples will help you to understand the usage of javax.security.auth.login.Configuration. These source code samples are taken from different open source projects.

Example 1
Project: jboss-seam-2.3.0.Final-Hibernate.3-master  File: SecurityTest.java View source code
private Configuration createMockJAASConfiguration() {
    return new Configuration() {

        private AppConfigurationEntry[] aces = { new AppConfigurationEntry(MockLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, new HashMap<String, String>()) };

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return aces;
        }

        @Override
        public void refresh() {
        }
    };
}
Example 2
Project: seam-2.2-master  File: SecurityTest.java View source code
private Configuration createMockJAASConfiguration() {
    return new Configuration() {

        private AppConfigurationEntry[] aces = { new AppConfigurationEntry(MockLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, new HashMap<String, String>()) };

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return aces;
        }

        @Override
        public void refresh() {
        }
    };
}
Example 3
Project: seam-revisited-master  File: Configuration.java View source code
protected javax.security.auth.login.Configuration createConfiguration() {
    return new javax.security.auth.login.Configuration() {

        private AppConfigurationEntry[] aces = { createAppConfigurationEntry() };

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return DEFAULT_JAAS_CONFIG_NAME.equals(name) ? aces : null;
        }

        @Override
        public void refresh() {
        }
    };
}
Example 4
Project: seam2jsf2-master  File: SecurityTest.java View source code
private Configuration createMockJAASConfiguration() {
    return new Configuration() {

        private AppConfigurationEntry[] aces = { new AppConfigurationEntry(MockLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, new HashMap<String, String>()) };

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return aces;
        }

        @Override
        public void refresh() {
        }
    };
}
Example 5
Project: taylor-seam-jsf2-master  File: Configuration.java View source code
protected javax.security.auth.login.Configuration createConfiguration() {
    return new javax.security.auth.login.Configuration() {

        private AppConfigurationEntry[] aces = { createAppConfigurationEntry() };

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return DEFAULT_JAAS_CONFIG_NAME.equals(name) ? aces : null;
        }

        @Override
        public void refresh() {
        }
    };
}
Example 6
Project: kylo-master  File: JaasAuthConfig.java View source code
@Bean(name = UI_AUTH_PROVIDER)
public AuthenticationProvider uiAuthenticationProvider(@Named("jaasConfiguration") javax.security.auth.login.Configuration config, List<AuthorityGranter> authorityGranters) {
    DefaultJaasAuthenticationProvider provider = new DefaultJaasAuthenticationProvider();
    provider.setConfiguration(config);
    provider.setAuthorityGranters(authorityGranters.toArray(new AuthorityGranter[authorityGranters.size()]));
    provider.setLoginContextName(JAAS_UI);
    return provider;
}
Example 7
Project: aries-master  File: JAASHelper.java View source code
public static <T> void doAs(final String[] groups, PrivilegedAction<T> action) {
    Configuration config = new Configuration() {

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            Map<String, Object> options = new HashMap<String, Object>();
            // The user does not matter
            options.put("username", "dummy");
            options.put("groups", groups);
            AppConfigurationEntry entry = new AppConfigurationEntry(SimpleLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, options);
            return new AppConfigurationEntry[] { entry };
        }
    };
    try {
        LoginContext lc = new LoginContext("test", new Subject(), null, config);
        lc.login();
        Subject.doAs(lc.getSubject(), action);
        lc.logout();
    } catch (LoginException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
Example 8
Project: flink-master  File: TestingSecurityContext.java View source code
public static void install(SecurityUtils.SecurityConfiguration config, Map<String, ClientSecurityConfiguration> clientSecurityConfigurationMap) throws Exception {
    SecurityUtils.install(config);
    // install dynamic JAAS entries
    checkArgument(config.getSecurityModules().contains(JaasModule.class));
    DynamicConfiguration jaasConf = (DynamicConfiguration) javax.security.auth.login.Configuration.getConfiguration();
    for (Map.Entry<String, ClientSecurityConfiguration> e : clientSecurityConfigurationMap.entrySet()) {
        AppConfigurationEntry entry = KerberosUtils.keytabEntry(e.getValue().getKeytab(), e.getValue().getPrincipal());
        jaasConf.addAppConfigurationEntry(e.getKey(), entry);
    }
}
Example 9
Project: cdi-tck-master  File: PrincipalInjectedBean.java View source code
protected javax.security.auth.login.Configuration createConfiguration() {
    return new javax.security.auth.login.Configuration() {

        private AppConfigurationEntry[] aces = { createAppConfigurationEntry() };

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return DEFAULT_JAAS_CONFIG_NAME.equals(name) ? aces : null;
        }

        @Override
        public void refresh() {
        }
    };
}
Example 10
Project: jbosstools-javaee-master  File: PrincipalInjectedBean.java View source code
protected javax.security.auth.login.Configuration createConfiguration() {
    return new javax.security.auth.login.Configuration() {

        private AppConfigurationEntry[] aces = { createAppConfigurationEntry() };

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return DEFAULT_JAAS_CONFIG_NAME.equals(name) ? aces : null;
        }

        @Override
        public void refresh() {
        }
    };
}
Example 11
Project: JBossAS51-master  File: SecurityDomainTolerateUnitTestCase.java View source code
/**
    * Setup the test suite.
    */
public static Test suite() throws Exception {
    TestSuite suite = new TestSuite();
    suite.addTest(new TestSuite(SecurityDomainTolerateUnitTestCase.class));
    // Create an initializer for the test suite
    TestSetup wrapper = new JBossTestSetup(suite) {

        @Override
        protected void setUp() throws Exception {
            super.setUp();
            Configuration.setConfiguration(XMLLoginConfigImpl.getInstance());
            redeploy("sdtolerate.ear");
            redeploy(getResourceURL(login_config));
            flushAuthCache();
        }

        @Override
        protected void tearDown() throws Exception {
            undeploy(getResourceURL(login_config));
            undeploy("sdtolerate.ear");
            super.tearDown();
        }
    };
    return wrapper;
}
Example 12
Project: JBossAS_5_1_EDG-master  File: SecurityDomainTolerateUnitTestCase.java View source code
/**
    * Setup the test suite.
    */
public static Test suite() throws Exception {
    TestSuite suite = new TestSuite();
    suite.addTest(new TestSuite(SecurityDomainTolerateUnitTestCase.class));
    // Create an initializer for the test suite
    TestSetup wrapper = new JBossTestSetup(suite) {

        @Override
        protected void setUp() throws Exception {
            super.setUp();
            Configuration.setConfiguration(XMLLoginConfigImpl.getInstance());
            redeploy("sdtolerate.ear");
            redeploy(getResourceURL(login_config));
            flushAuthCache();
        }

        @Override
        protected void tearDown() throws Exception {
            undeploy(getResourceURL(login_config));
            undeploy("sdtolerate.ear");
            super.tearDown();
        }
    };
    return wrapper;
}
Example 13
Project: datacollector-master  File: SdcKrb5HttpClientConfigurer.java View source code
public static boolean setSPNegoAuth(DefaultHttpClient httpClient) {
    // Begin change for SDC-2962
    // Instead of checking existence of JAAS file, do the following if solr kerberos is enabled
    //String configValue = System.getProperty("java.security.auth.login.config");
    //if(configValue != null) {
    //logger.info("Setting up SPNego auth with config: " + configValue);
    // End change for SDC-2962
    String useSubjectCredsProp = "javax.security.auth.useSubjectCredsOnly";
    String useSubjectCredsVal = System.getProperty("javax.security.auth.useSubjectCredsOnly");
    if (useSubjectCredsVal == null) {
        System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    } else if (!useSubjectCredsVal.toLowerCase(Locale.ROOT).equals("false")) {
        logger.warn("System Property: javax.security.auth.useSubjectCredsOnly set to: " + useSubjectCredsVal + " not false.  SPNego authentication may not be successful.");
    }
    // Change for SDC-2962
    //Configuration.setConfiguration(jaasConf);
    httpClient.getAuthSchemes().register("negotiate", new SPNegoSchemeFactory(true));
    Credentials use_jaas_creds = new Credentials() {

        public String getPassword() {
            return null;
        }

        public Principal getUserPrincipal() {
            return null;
        }
    };
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, use_jaas_creds);
    return true;
/*} else {
      httpClient.getCredentialsProvider().clear();
      return false;
    }*/
}
Example 14
Project: lucene-solr-master  File: KerberosTestServices.java View source code
public KerberosTestServices build() throws Exception {
    final MiniKdc kdc = kdcWorkDir != null ? getKdc(kdcWorkDir) : null;
    final Configuration oldConfig = clientPrincipal != null ? Configuration.getConfiguration() : null;
    JaasConfiguration jaasConfiguration = null;
    if (clientPrincipal != null) {
        jaasConfiguration = (appName == null) ? new JaasConfiguration(clientPrincipal, clientKeytab, serverPrincipal, serverKeytab) : new JaasConfiguration(clientPrincipal, clientKeytab, appName);
    }
    return new KerberosTestServices(kdc, jaasConfiguration, oldConfig, savedLocale);
}
Example 15
Project: camel-master  File: HdfsProducer.java View source code
@Override
protected void doStart() throws Exception {
    // need to remember auth as Hadoop will override that, which otherwise means the Auth is broken afterwards
    Configuration auth = HdfsComponent.getJAASConfiguration();
    try {
        super.doStart();
        // setup hdfs if configured to do on startup
        if (getEndpoint().getConfig().isConnectOnStartup()) {
            ostream = setupHdfs(true);
        }
        SplitStrategy idleStrategy = null;
        for (SplitStrategy strategy : config.getSplitStrategies()) {
            if (strategy.type == SplitStrategyType.IDLE) {
                idleStrategy = strategy;
                break;
            }
        }
        if (idleStrategy != null) {
            scheduler = getEndpoint().getCamelContext().getExecutorServiceManager().newSingleThreadScheduledExecutor(this, "HdfsIdleCheck");
            log.debug("Creating IdleCheck task scheduled to run every {} millis", config.getCheckIdleInterval());
            scheduler.scheduleAtFixedRate(new IdleCheck(idleStrategy), config.getCheckIdleInterval(), config.getCheckIdleInterval(), TimeUnit.MILLISECONDS);
        }
    } finally {
        HdfsComponent.setJAASConfiguration(auth);
    }
}
Example 16
Project: incubator-wave-master  File: ServerModule.java View source code
@Override
protected void configure() {
    bind(WaveServerImpl.class).in(Singleton.class);
    // Receive updates from the outside world, and push them into our local Wave
    // Server.
    bind(WaveletFederationListener.Factory.class).annotatedWith(FederationRemoteBridge.class).to(WaveServerImpl.class);
    // Provide history and respond to submits about our own local waves.
    bind(WaveletFederationProvider.class).annotatedWith(FederationHostBridge.class).to(WaveServerImpl.class);
    install(waveServerModule);
    TypeLiteral<List<String>> certs = new TypeLiteral<List<String>>() {
    };
    bind(certs).annotatedWith(Names.named("certs")).toInstance(Arrays.<String>asList());
    bind(ProtoSerializer.class).in(Singleton.class);
    bind(Configuration.class).toInstance(Configuration.getConfiguration());
    bind(SessionManager.class).to(SessionManagerImpl.class).in(Singleton.class);
    bind(ServerRpcProvider.class).in(Singleton.class);
    bind(RobotRegistrar.class).to(RobotRegistrarImpl.class);
    requestStaticInjection(WebSocketChannel.class);
}
Example 17
Project: jdk7u-jdk-master  File: ConfigFile.java View source code
/**
     * Read and initialize the entire login Configuration.
     *
     * <p>
     *
     * @exception IOException if the Configuration can not be initialized. <p>
     * @exception SecurityException if the caller does not have permission
     *                          to initialize the Configuration.
     */
private void init(URL url) throws IOException {
    boolean initialized = false;
    FileReader fr = null;
    String sep = File.separator;
    if ("false".equals(System.getProperty("policy.expandProperties"))) {
        expandProp = false;
    }
    // new configuration
    HashMap<String, LinkedList<AppConfigurationEntry>> newConfig = new HashMap<>();
    if (url != null) {
        /**
             * If the caller specified a URI via Configuration.getInstance,
             * we only read from that URI
             */
        if (debugConfig != null) {
            debugConfig.println("reading " + url);
        }
        init(url, newConfig);
        configuration = newConfig;
        return;
    }
    /**
         * Caller did not specify URI via Configuration.getInstance.
         * Read from URLs listed in the java.security properties file.
         */
    String allowSys = java.security.Security.getProperty("policy.allowSystemProperty");
    if ("true".equalsIgnoreCase(allowSys)) {
        String extra_config = System.getProperty("java.security.auth.login.config");
        if (extra_config != null) {
            boolean overrideAll = false;
            if (extra_config.startsWith("=")) {
                overrideAll = true;
                extra_config = extra_config.substring(1);
            }
            try {
                extra_config = PropertyExpander.expand(extra_config);
            } catch (PropertyExpander.ExpandException peee) {
                MessageFormat form = new MessageFormat(ResourcesMgr.getString("Unable.to.properly.expand.config", "sun.security.util.AuthResources"));
                Object[] source = { extra_config };
                throw new IOException(form.format(source));
            }
            URL configURL = null;
            try {
                configURL = new URL(extra_config);
            } catch (java.net.MalformedURLException mue) {
                File configFile = new File(extra_config);
                if (configFile.exists()) {
                    configURL = configFile.toURI().toURL();
                } else {
                    MessageFormat form = new MessageFormat(ResourcesMgr.getString("extra.config.No.such.file.or.directory.", "sun.security.util.AuthResources"));
                    Object[] source = { extra_config };
                    throw new IOException(form.format(source));
                }
            }
            if (debugConfig != null) {
                debugConfig.println("reading " + configURL);
            }
            init(configURL, newConfig);
            initialized = true;
            if (overrideAll) {
                if (debugConfig != null) {
                    debugConfig.println("overriding other policies!");
                }
                configuration = newConfig;
                return;
            }
        }
    }
    int n = 1;
    String config_url;
    while ((config_url = java.security.Security.getProperty("login.config.url." + n)) != null) {
        try {
            config_url = PropertyExpander.expand(config_url).replace(File.separatorChar, '/');
            if (debugConfig != null) {
                debugConfig.println("\tReading config: " + config_url);
            }
            init(new URL(config_url), newConfig);
            initialized = true;
        } catch (PropertyExpander.ExpandException peee) {
            MessageFormat form = new MessageFormat(ResourcesMgr.getString("Unable.to.properly.expand.config", "sun.security.util.AuthResources"));
            Object[] source = { config_url };
            throw new IOException(form.format(source));
        }
        n++;
    }
    if (initialized == false && n == 1 && config_url == null) {
        // get the config from the user's home directory
        if (debugConfig != null) {
            debugConfig.println("\tReading Policy " + "from ~/.java.login.config");
        }
        config_url = System.getProperty("user.home");
        String userConfigFile = config_url + File.separatorChar + ".java.login.config";
        // at all. Returns an empty Configuration instead.
        if (new File(userConfigFile).exists()) {
            init(new File(userConfigFile).toURI().toURL(), newConfig);
        }
    }
    configuration = newConfig;
}
Example 18
Project: openjdk-master  File: DynamicConfigurationTest.java View source code
public static void main(String... args) {
    String rightConfigName = "PT";
    String wrongConfigName = "NT";
    char[] rightPwd = new char[] { 't', 'e', 's', 't', 'P', 'a', 's', 's', 'w', 'o', 'r', 'd', '1' };
    char[] wrongPwd = new char[] { 'w', 'r', 'o', 'n', 'g', 'P', 'a', 's', 's', 'w', 'o', 'r', 'd' };
    // Test with wrong configuration name
    // Expect LoginException when initiate a new LoginContext object
    testConfigName(wrongConfigName, true);
    System.out.println("Wrong Config Name Test passed ");
    // Spedify two loginModules: SmartLoginModule and DummyLoginModule
    // Flags: required-required
    // Test with right password for SmartLoginModule
    // No exception is expected
    Configuration cf = new MyConfiguration();
    testLogin(rightConfigName, rightPwd, cf, false);
    System.out.println("Positive test passed");
    // Spedify two loginModules: SmartLoginModule and DummyLoginModule
    // Flags: required-required
    // Test with wrong password for SmartLoginModule
    // Expect LoginException by calling LoginContext.login() method
    testLogin(rightConfigName, wrongPwd, cf, true);
    System.out.println("Should fail test passed");
    // Spedify two loginModules: SmartLoginModule and DummyLoginModule
    // Change the flags from required-required to optional-sufficient
    // Test with wrong password for SmartLoginModule, while DummyLoginModule
    // always passes
    // No Exception is expected
    cf = new MyConfiguration(true);
    testLogin(rightConfigName, wrongPwd, cf, false);
    System.out.println("One module fails where are other module succeeeds " + "Test passed with optional-sufficient flags");
}
Example 19
Project: openjdk8-jdk-master  File: ConfigFile.java View source code
/**
         * Read and initialize the entire login Configuration from the
         * configured URL.
         *
         * @throws IOException if the Configuration can not be initialized
         * @throws SecurityException if the caller does not have permission
         *                           to initialize the Configuration
         */
private void init() throws IOException {
    boolean initialized = false;
    // For policy.expandProperties, check if either a security or system
    // property is set to false (old code erroneously checked the system
    // prop so we must check both to preserve compatibility).
    String expand = Security.getProperty("policy.expandProperties");
    if (expand == null) {
        expand = System.getProperty("policy.expandProperties");
    }
    if ("false".equals(expand)) {
        expandProp = false;
    }
    // new configuration
    Map<String, List<AppConfigurationEntry>> newConfig = new HashMap<>();
    if (url != null) {
        /**
                 * If the caller specified a URI via Configuration.getInstance,
                 * we only read from that URI
                 */
        if (debugConfig != null) {
            debugConfig.println("reading " + url);
        }
        init(url, newConfig);
        configuration = newConfig;
        return;
    }
    /**
             * Caller did not specify URI via Configuration.getInstance.
             * Read from URLs listed in the java.security properties file.
             */
    String allowSys = Security.getProperty("policy.allowSystemProperty");
    if ("true".equalsIgnoreCase(allowSys)) {
        String extra_config = System.getProperty("java.security.auth.login.config");
        if (extra_config != null) {
            boolean overrideAll = false;
            if (extra_config.startsWith("=")) {
                overrideAll = true;
                extra_config = extra_config.substring(1);
            }
            try {
                extra_config = PropertyExpander.expand(extra_config);
            } catch (PropertyExpander.ExpandException peee) {
                throw ioException("Unable.to.properly.expand.config", extra_config);
            }
            URL configURL = null;
            try {
                configURL = new URL(extra_config);
            } catch (MalformedURLException mue) {
                File configFile = new File(extra_config);
                if (configFile.exists()) {
                    configURL = configFile.toURI().toURL();
                } else {
                    throw ioException("extra.config.No.such.file.or.directory.", extra_config);
                }
            }
            if (debugConfig != null) {
                debugConfig.println("reading " + configURL);
            }
            init(configURL, newConfig);
            initialized = true;
            if (overrideAll) {
                if (debugConfig != null) {
                    debugConfig.println("overriding other policies!");
                }
                configuration = newConfig;
                return;
            }
        }
    }
    int n = 1;
    String config_url;
    while ((config_url = Security.getProperty("login.config.url." + n)) != null) {
        try {
            config_url = PropertyExpander.expand(config_url).replace(File.separatorChar, '/');
            if (debugConfig != null) {
                debugConfig.println("\tReading config: " + config_url);
            }
            init(new URL(config_url), newConfig);
            initialized = true;
        } catch (PropertyExpander.ExpandException peee) {
            throw ioException("Unable.to.properly.expand.config", config_url);
        }
        n++;
    }
    if (initialized == false && n == 1 && config_url == null) {
        // get the config from the user's home directory
        if (debugConfig != null) {
            debugConfig.println("\tReading Policy " + "from ~/.java.login.config");
        }
        config_url = System.getProperty("user.home");
        String userConfigFile = config_url + File.separatorChar + ".java.login.config";
        // at all. Returns an empty Configuration instead.
        if (new File(userConfigFile).exists()) {
            init(new File(userConfigFile).toURI().toURL(), newConfig);
        }
    }
    configuration = newConfig;
}
Example 20
Project: swellrt-master  File: ServerModule.java View source code
@Override
protected void configure() {
    bind(WaveServerImpl.class).in(Singleton.class);
    // Receive updates from the outside world, and push them into our local Wave
    // Server.
    bind(WaveletFederationListener.Factory.class).annotatedWith(FederationRemoteBridge.class).to(WaveServerImpl.class);
    // Provide history and respond to submits about our own local waves.
    bind(WaveletFederationProvider.class).annotatedWith(FederationHostBridge.class).to(WaveServerImpl.class);
    install(waveServerModule);
    TypeLiteral<List<String>> certs = new TypeLiteral<List<String>>() {
    };
    bind(certs).annotatedWith(Names.named("certs")).toInstance(Arrays.<String>asList());
    bind(ProtoSerializer.class).in(Singleton.class);
    bind(Configuration.class).toInstance(Configuration.getConfiguration());
    bind(SessionManager.class).to(SessionManagerImpl.class).in(Singleton.class);
    bind(ServerRpcProvider.class).in(Singleton.class);
    // bind(RobotRegistrar.class).to(RobotRegistrarImpl.class);
    requestStaticInjection(WebSocketChannel.class);
}
Example 21
Project: Wave-master  File: ServerModule.java View source code
@Override
protected void configure() {
    bind(WaveServerImpl.class).in(Singleton.class);
    // Receive updates from the outside world, and push them into our local Wave
    // Server.
    bind(WaveletFederationListener.Factory.class).annotatedWith(FederationRemoteBridge.class).to(WaveServerImpl.class);
    // Provide history and respond to submits about our own local waves.
    bind(WaveletFederationProvider.class).annotatedWith(FederationHostBridge.class).to(WaveServerImpl.class);
    bind(Executor.class).annotatedWith(LookupExecutor.class).toInstance(Executors.newFixedThreadPool(lookupCount));
    install(new WaveServerModule(enableFederation, listenerCount, waveletLoadCount, deltaPersistCount, storageContinuationCount));
    TypeLiteral<List<String>> certs = new TypeLiteral<List<String>>() {
    };
    bind(certs).annotatedWith(Names.named("certs")).toInstance(Arrays.<String>asList());
    bind(ProtoSerializer.class).in(Singleton.class);
    bind(Configuration.class).toInstance(Configuration.getConfiguration());
    bind(SessionManager.class).to(SessionManagerImpl.class).in(Singleton.class);
    bind(org.eclipse.jetty.server.SessionManager.class).to(HashSessionManager.class).in(Singleton.class);
    bind(ServerRpcProvider.class).in(Singleton.class);
    bind(RobotRegistrar.class).to(RobotRegistrarImpl.class);
}
Example 22
Project: wave-protocol-master  File: ServerModule.java View source code
@Override
protected void configure() {
    // Receive updates from the outside world, and push them into our local Wave
    // Server.
    bind(WaveletFederationListener.Factory.class).annotatedWith(FederationRemoteBridge.class).to(WaveServerImpl.class);
    // Provide history and respond to submits about our own local waves.
    bind(WaveletFederationProvider.class).annotatedWith(FederationHostBridge.class).to(WaveServerImpl.class);
    install(new WaveServerModule(enableFederation));
    TypeLiteral<List<String>> certs = new TypeLiteral<List<String>>() {
    };
    bind(certs).annotatedWith(Names.named("certs")).toInstance(Arrays.<String>asList());
    bind(ProtoSerializer.class).in(Singleton.class);
    bind(Configuration.class).toInstance(Configuration.getConfiguration());
    bind(SessionManager.class).to(SessionManagerImpl.class).in(Singleton.class);
    bind(org.eclipse.jetty.server.SessionManager.class).to(HashSessionManager.class).in(Singleton.class);
    bind(ServerRpcProvider.class).in(Singleton.class);
    bind(RobotRegistrar.class).to(RobotRegistrarImpl.class);
}
Example 23
Project: WaveInCloud-master  File: ServerModule.java View source code
@Override
protected void configure() {
    // Receive updates from the outside world, and push them into our local Wave
    // Server.
    bind(WaveletFederationListener.Factory.class).annotatedWith(FederationRemoteBridge.class).to(WaveServerImpl.class);
    // Provide history and respond to submits about our own local waves.
    bind(WaveletFederationProvider.class).annotatedWith(FederationHostBridge.class).to(WaveServerImpl.class);
    install(new WaveServerModule(enableFederation));
    TypeLiteral<List<String>> certs = new TypeLiteral<List<String>>() {
    };
    bind(certs).annotatedWith(Names.named("certs")).toInstance(Arrays.<String>asList());
    bind(ProtoSerializer.class).in(Singleton.class);
    bind(Configuration.class).toInstance(Configuration.getConfiguration());
    bind(SessionManager.class).to(SessionManagerImpl.class).in(Singleton.class);
    bind(org.eclipse.jetty.server.SessionManager.class).to(HashSessionManager.class).in(Singleton.class);
    bind(ServerRpcProvider.class).in(Singleton.class);
}
Example 24
Project: alluxio-master  File: LoginUser.java View source code
/**
   * Logs in based on the LoginModules.
   *
   * @return the login user
   */
private static User login() throws UnauthenticatedException {
    AuthType authType = Configuration.getEnum(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.class);
    checkSecurityEnabled(authType);
    Subject subject = new Subject();
    try {
        // Use the class loader of User.class to construct the LoginContext. LoginContext uses this
        // class loader to dynamically instantiate login modules. This enables
        // Subject#getPrincipals to use reflection to search for User.class instances.
        LoginContext loginContext = createLoginContext(authType, subject, User.class.getClassLoader(), new LoginModuleConfiguration());
        loginContext.login();
    } catch (LoginException e) {
        throw new UnauthenticatedException("Failed to login: " + e.getMessage(), e);
    }
    Set<User> userSet = subject.getPrincipals(User.class);
    if (userSet.isEmpty()) {
        throw new UnauthenticatedException("Failed to login: No Alluxio User is found.");
    }
    if (userSet.size() > 1) {
        StringBuilder msg = new StringBuilder("Failed to login: More than one Alluxio Users are found:");
        for (User user : userSet) {
            msg.append(" ").append(user.toString());
        }
        throw new UnauthenticatedException(msg.toString());
    }
    return userSet.iterator().next();
}
Example 25
Project: ambari-master  File: KerberosChecker.java View source code
/**
   * Checks Ambari Server with a Kerberos principal and keytab to allow views
   * to authenticate via SPNEGO against cluster components.
   *
   * @throws AmbariException
   */
public static void checkJaasConfiguration() throws AmbariException {
    if (config.isKerberosJaasConfigurationCheckEnabled()) {
        LOG.info("Checking Ambari Server Kerberos credentials.");
        String jaasConfPath = System.getProperty(JAVA_SECURITY_AUTH_LOGIN_CONFIG);
        javax.security.auth.login.Configuration jaasConf = javax.security.auth.login.Configuration.getConfiguration();
        AppConfigurationEntry[] jaasConfEntries = jaasConf.getAppConfigurationEntry(HTTP_SPNEGO_STANDARD_ENTRY);
        if (jaasConfEntries == null) {
            LOG.warn("Can't find " + HTTP_SPNEGO_STANDARD_ENTRY + " entry in " + jaasConfPath);
        } else {
            boolean krb5LoginModulePresent = false;
            for (AppConfigurationEntry ace : jaasConfEntries) {
                if (KRB5_LOGIN_MODULE.equals(ace.getLoginModuleName())) {
                    krb5LoginModulePresent = true;
                    Map<String, ?> options = ace.getOptions();
                    if ((options != null)) {
                        if (options.containsKey("keyTab")) {
                            String keytabPath = (String) options.get("keyTab");
                            File keytabFile = new File(keytabPath);
                            if (!keytabFile.exists()) {
                                LOG.warn(keytabPath + " doesn't exist.");
                            } else if (!keytabFile.canRead()) {
                                LOG.warn("Unable to read " + keytabPath + " Please check the file access permissions for user " + System.getProperty("user.name"));
                            }
                        } else {
                            LOG.warn("Can't find keyTab option in " + KRB5_LOGIN_MODULE + " module of " + HTTP_SPNEGO_STANDARD_ENTRY + " entry in " + jaasConfPath);
                        }
                        if (!options.containsKey("principal")) {
                            LOG.warn("Can't find principal option in " + KRB5_LOGIN_MODULE + " module of " + HTTP_SPNEGO_STANDARD_ENTRY + " entry in " + jaasConfPath);
                        }
                    }
                }
            }
            if (!krb5LoginModulePresent) {
                LOG.warn("Can't find " + KRB5_LOGIN_MODULE + " module in " + HTTP_SPNEGO_STANDARD_ENTRY + " entry in " + jaasConfPath);
            }
        }
        try {
            LoginContext loginContext = loginContextHelper.createLoginContext(HTTP_SPNEGO_STANDARD_ENTRY);
            loginContext.login();
            loginContext.logout();
        } catch (LoginException le) {
            LOG.error(le.getMessage());
            throw new AmbariException("Ambari Server Kerberos credentials check failed. \n" + "Check KDC availability and JAAS configuration in " + jaasConfPath);
        }
        LOG.info("Ambari Server Kerberos credentials check passed.");
    } else {
        LOG.info("Skipping Ambari Server Kerberos credentials check.");
    }
}
Example 26
Project: hadoop-master  File: TestSecureRegistry.java View source code
/**
  * this is a cut and paste of some of the ZK internal code that was
   * failing on windows and swallowing its exceptions
   */
@Test
public void testLowlevelZKSaslLogin() throws Throwable {
    RegistrySecurity.bindZKToServerJAASContext(ZOOKEEPER_SERVER_CONTEXT);
    String serverSection = System.getProperty(ZooKeeperSaslServer.LOGIN_CONTEXT_NAME_KEY, ZooKeeperSaslServer.DEFAULT_LOGIN_CONTEXT_NAME);
    assertEquals(ZOOKEEPER_SERVER_CONTEXT, serverSection);
    AppConfigurationEntry entries[];
    entries = javax.security.auth.login.Configuration.getConfiguration().getAppConfigurationEntry(serverSection);
    assertNotNull("null entries", entries);
    SaslServerCallbackHandler saslServerCallbackHandler = new SaslServerCallbackHandler(javax.security.auth.login.Configuration.getConfiguration());
    Login login = new Login(serverSection, saslServerCallbackHandler);
    try {
        login.startThreadIfNeeded();
    } finally {
        login.shutdown();
    }
}
Example 27
Project: hops-master  File: TestSecureRegistry.java View source code
/**
  * this is a cut and paste of some of the ZK internal code that was
   * failing on windows and swallowing its exceptions
   */
@Test
public void testLowlevelZKSaslLogin() throws Throwable {
    RegistrySecurity.bindZKToServerJAASContext(ZOOKEEPER_SERVER_CONTEXT);
    String serverSection = System.getProperty(ZooKeeperSaslServer.LOGIN_CONTEXT_NAME_KEY, ZooKeeperSaslServer.DEFAULT_LOGIN_CONTEXT_NAME);
    assertEquals(ZOOKEEPER_SERVER_CONTEXT, serverSection);
    AppConfigurationEntry entries[];
    entries = javax.security.auth.login.Configuration.getConfiguration().getAppConfigurationEntry(serverSection);
    assertNotNull("null entries", entries);
    SaslServerCallbackHandler saslServerCallbackHandler = new SaslServerCallbackHandler(javax.security.auth.login.Configuration.getConfiguration());
    Login login = new Login(serverSection, saslServerCallbackHandler);
    try {
        login.startThreadIfNeeded();
    } finally {
        login.shutdown();
    }
}
Example 28
Project: picketbox-master  File: LdapAttributeMappingProviderUnitTestCase.java View source code
protected void setUp() throws Exception {
    super.setUp();
    XMLLoginConfigImpl xmlLogin = XMLLoginConfigImpl.getInstance();
    Configuration.setConfiguration(xmlLogin);
    ApplicationPolicy ap = new ApplicationPolicy("test");
    SecurityConfiguration.addApplicationPolicy(ap);
    //Let us add the ldapAttributes.ldif
    String fileName = targetDir + "ldap" + fs + "ldapAttributes.ldif";
    boolean op = util.addLDIF(serverHost, port, adminDN, adminPW, new File(fileName).toURI().toURL());
    assertTrue(op);
}
Example 29
Project: tachyon-master  File: LoginUser.java View source code
/**
   * Logs in based on the LoginModules.
   *
   * @return the login user
   */
private static User login() throws UnauthenticatedException {
    AuthType authType = Configuration.getEnum(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.class);
    checkSecurityEnabled(authType);
    Subject subject = new Subject();
    try {
        // Use the class loader of User.class to construct the LoginContext. LoginContext uses this
        // class loader to dynamically instantiate login modules. This enables
        // Subject#getPrincipals to use reflection to search for User.class instances.
        LoginContext loginContext = createLoginContext(authType, subject, User.class.getClassLoader(), new LoginModuleConfiguration());
        loginContext.login();
    } catch (LoginException e) {
        throw new UnauthenticatedException("Failed to login: " + e.getMessage(), e);
    }
    Set<User> userSet = subject.getPrincipals(User.class);
    if (userSet.isEmpty()) {
        throw new UnauthenticatedException("Failed to login: No Alluxio User is found.");
    }
    if (userSet.size() > 1) {
        StringBuilder msg = new StringBuilder("Failed to login: More than one Alluxio Users are found:");
        for (User user : userSet) {
            msg.append(" ").append(user.toString());
        }
        throw new UnauthenticatedException(msg.toString());
    }
    return userSet.iterator().next();
}
Example 30
Project: hive-master  File: LlapZookeeperRegistryImpl.java View source code
/**
   * Get the ensemble server addresses from the configuration. The format is: host1:port,
   * host2:port..
   *
   * @param conf
   **/
private String getQuorumServers(Configuration conf) {
    String[] hosts = conf.getTrimmedStrings(ConfVars.HIVE_ZOOKEEPER_QUORUM.varname);
    String port = conf.get(ConfVars.HIVE_ZOOKEEPER_CLIENT_PORT.varname, ConfVars.HIVE_ZOOKEEPER_CLIENT_PORT.getDefaultValue());
    StringBuilder quorum = new StringBuilder();
    for (int i = 0; i < hosts.length; i++) {
        quorum.append(hosts[i].trim());
        if (!hosts[i].contains(":")) {
            // if the hostname doesn't contain a port, add the configured port to hostname
            quorum.append(":");
            quorum.append(port);
        }
        if (i != hosts.length - 1) {
            quorum.append(",");
        }
    }
    return quorum.toString();
}
Example 31
Project: incubator-atlas-master  File: InMemoryJAASConfigurationTest.java View source code
@Test(enabled = false)
public void testGetAppConfigurationEntryStringForKafkaClient() {
    AppConfigurationEntry[] entries = Configuration.getConfiguration().getAppConfigurationEntry("KafkaClient");
    Assert.assertNotNull(entries);
    Assert.assertEquals(1, entries.length);
    String principal = (String) entries[0].getOptions().get("principal");
    Assert.assertNotNull(principal);
    String[] components = principal.split("[/@]");
    Assert.assertEquals(3, components.length);
    Assert.assertEquals(false, StringUtils.equalsIgnoreCase(components[1], "_HOST"));
}
Example 32
Project: kafka-master  File: JaasContext.java View source code
private static JaasContext defaultContext(JaasContext.Type contextType, String listenerContextName, String globalContextName) {
    String jaasConfigFile = System.getProperty(JaasUtils.JAVA_LOGIN_CONFIG_PARAM);
    if (jaasConfigFile == null) {
        if (contextType == Type.CLIENT) {
            LOG.debug("System property '" + JaasUtils.JAVA_LOGIN_CONFIG_PARAM + "' and Kafka SASL property '" + SaslConfigs.SASL_JAAS_CONFIG + "' are not set, using default JAAS configuration.");
        } else {
            LOG.debug("System property '" + JaasUtils.JAVA_LOGIN_CONFIG_PARAM + "' is not set, using default JAAS " + "configuration.");
        }
    }
    Configuration jaasConfig = Configuration.getConfiguration();
    AppConfigurationEntry[] configEntries = null;
    String contextName = globalContextName;
    if (listenerContextName != null) {
        configEntries = jaasConfig.getAppConfigurationEntry(listenerContextName);
        if (configEntries != null)
            contextName = listenerContextName;
    }
    if (configEntries == null)
        configEntries = jaasConfig.getAppConfigurationEntry(globalContextName);
    if (configEntries == null) {
        String listenerNameText = listenerContextName == null ? "" : " or '" + listenerContextName + "'";
        String errorMessage = "Could not find a '" + globalContextName + "'" + listenerNameText + " entry in the JAAS " + "configuration. System property '" + JaasUtils.JAVA_LOGIN_CONFIG_PARAM + "' is " + (jaasConfigFile == null ? "not set" : jaasConfigFile);
        throw new IllegalArgumentException(errorMessage);
    }
    return new JaasContext(contextName, contextType, jaasConfig);
}
Example 33
Project: ManagedRuntimeInitiative-master  File: ConfigFile.java View source code
/**
     * Read and initialize the entire login Configuration.
     *
     * <p>
     *
     * @exception IOException if the Configuration can not be initialized. <p>
     * @exception SecurityException if the caller does not have permission
     *                          to initialize the Configuration.
     */
private void init(URL url) throws IOException {
    boolean initialized = false;
    FileReader fr = null;
    String sep = File.separator;
    if ("false".equals(System.getProperty("policy.expandProperties"))) {
        expandProp = false;
    }
    // new configuration
    HashMap<String, LinkedList<AppConfigurationEntry>> newConfig = new HashMap<String, LinkedList<AppConfigurationEntry>>();
    if (url != null) {
        /**
             * If the caller specified a URI via Configuration.getInstance,
             * we only read from that URI
             */
        if (debugConfig != null) {
            debugConfig.println("reading " + url);
        }
        init(url, newConfig);
        configuration = newConfig;
        return;
    }
    /**
         * Caller did not specify URI via Configuration.getInstance.
         * Read from URLs listed in the java.security properties file.
         */
    String allowSys = java.security.Security.getProperty("policy.allowSystemProperty");
    if ("true".equalsIgnoreCase(allowSys)) {
        String extra_config = System.getProperty("java.security.auth.login.config");
        if (extra_config != null) {
            boolean overrideAll = false;
            if (extra_config.startsWith("=")) {
                overrideAll = true;
                extra_config = extra_config.substring(1);
            }
            try {
                extra_config = PropertyExpander.expand(extra_config);
            } catch (PropertyExpander.ExpandException peee) {
                MessageFormat form = new MessageFormat(ResourcesMgr.getString("Unable to properly expand config", "sun.security.util.AuthResources"));
                Object[] source = { extra_config };
                throw new IOException(form.format(source));
            }
            URL configURL = null;
            try {
                configURL = new URL(extra_config);
            } catch (java.net.MalformedURLException mue) {
                File configFile = new File(extra_config);
                if (configFile.exists()) {
                    configURL = configFile.toURI().toURL();
                } else {
                    MessageFormat form = new MessageFormat(ResourcesMgr.getString("extra_config (No such file or directory)", "sun.security.util.AuthResources"));
                    Object[] source = { extra_config };
                    throw new IOException(form.format(source));
                }
            }
            if (debugConfig != null) {
                debugConfig.println("reading " + configURL);
            }
            init(configURL, newConfig);
            initialized = true;
            if (overrideAll) {
                if (debugConfig != null) {
                    debugConfig.println("overriding other policies!");
                }
                configuration = newConfig;
                return;
            }
        }
    }
    int n = 1;
    String config_url;
    while ((config_url = java.security.Security.getProperty("login.config.url." + n)) != null) {
        try {
            config_url = PropertyExpander.expand(config_url).replace(File.separatorChar, '/');
            if (debugConfig != null) {
                debugConfig.println("\tReading config: " + config_url);
            }
            init(new URL(config_url), newConfig);
            initialized = true;
        } catch (PropertyExpander.ExpandException peee) {
            MessageFormat form = new MessageFormat(ResourcesMgr.getString("Unable to properly expand config", "sun.security.util.AuthResources"));
            Object[] source = { config_url };
            throw new IOException(form.format(source));
        }
        n++;
    }
    if (initialized == false && n == 1 && config_url == null) {
        // get the config from the user's home directory
        if (debugConfig != null) {
            debugConfig.println("\tReading Policy " + "from ~/.java.login.config");
        }
        config_url = System.getProperty("user.home");
        String userConfigFile = config_url + File.separatorChar + ".java.login.config";
        // at all. Returns an empty Configuration instead.
        if (new File(userConfigFile).exists()) {
            init(new File(userConfigFile).toURI().toURL(), newConfig);
        }
    }
    configuration = newConfig;
}
Example 34
Project: marketcetera-master  File: StrategyAgentRemotingConfigTest.java View source code
/**
     * Sets up the JAAS Configuration such that both Client's test Mock server
     * and remote-receiver's can work.
     */
static void setupConfiguration() {
    Configuration.setConfiguration(new Configuration() {

        public AppConfigurationEntry[] getAppConfigurationEntry(String inName) {
            if ("remoting-amq-domain".equals(inName)) {
                //the login module for the receiver module.
                return new AppConfigurationEntry[] { new AppConfigurationEntry(ClientLoginModule.class.getName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, Collections.unmodifiableMap(new HashMap<String, String>())) };
            } else if ("test-amq-domain".equals(inName)) {
                //the login module for mock server
                return new AppConfigurationEntry[] { new AppConfigurationEntry(MockLoginModule.class.getName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, Collections.unmodifiableMap(new HashMap<String, String>())) };
            }
            return null;
        }
    });
}
Example 35
Project: mssql-jdbc-master  File: JaasConfiguration.java View source code
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
    AppConfigurationEntry[] conf = delegate == null ? null : delegate.getAppConfigurationEntry(name);
    // In case where user did request another JAAS Configuration name, we expect he knows what he is doing.
    if (conf == null && name.equals(SQLServerDriverStringProperty.JAAS_CONFIG_NAME.getDefaultValue())) {
        return defaultValue;
    }
    return conf;
}
Example 36
Project: nuxeo-master  File: LoginConfiguration.java View source code
public void install(Provider provider) {
    holder.set(provider);
    int count = counter.incrementAndGet();
    if (count == 1) {
        context = new InstallContext(provider);
        Configuration.setConfiguration(this);
        LogFactory.getLog(LoginConfiguration.class).trace("installed login configuration", context.stacktrace);
    }
}
Example 37
Project: rt.equinox.bundles-master  File: SecurePlatformInternal.java View source code
/**
	 * Java docs specify that if multiple config files are passed in, they will be merged into one file.
	 * Hence, aside from implementation details, no priority information is specified by the order
	 * of config files. In this implementation we add customer's config file to the end of the list.
	 * 
	 * This method substitutes default login configuration:
	 * Configuration Inquiries -> ConfigurationFederator ->
	 * 		1) Extension Point supplied config providers;
	 * 		2) default Java config provider ("login.configuration.provider")
	 */
public void start() {
    if (running)
        return;
    // Kludge for the bug 215828 "JAAS and server-side Eclipse": for the time being configuration 
    // substitution is turned off if running on a server. It is likely possible to work around 
    // configuration substitution using Java 5 methods, but not Java 1.4
    BundleContext context = AuthPlugin.getDefault().getBundleContext();
    String vmType = context.getProperty(VM_PROPERTY);
    if (SERVER_VM.equals(vmType)) {
        defaultConfiguration = null;
        running = true;
        return;
    }
    try {
        defaultConfiguration = Configuration.getConfiguration();
    } catch (SecurityException e) {
        defaultConfiguration = null;
    }
    Configuration.setConfiguration(new ConfigurationFederator(defaultConfiguration));
    running = true;
}
Example 38
Project: tempto-master  File: KerberosAuthentication.java View source code
private static Configuration createKerberosConfiguration(String principal, String keytab) {
    Map<String, String> loginOptions = createLoginOptions(principal, keytab);
    return new Configuration() {

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return new AppConfigurationEntry[] { new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, loginOptions) };
        }
    };
}
Example 39
Project: Tstream-master  File: ThriftClient.java View source code
protected void flushClient(Map storm_conf, Integer timeout) throws Exception {
    try {
        flushHost();
        String[] host_port = masterHost.split(":");
        if (host_port.length != 2) {
            throw new InvalidParameterException("Host format error: " + masterHost);
        }
        String host = host_port[0];
        int port = Integer.parseInt(host_port[1]);
        LOG.info("Begin to connect " + host + ":" + port);
        // locate login configuration
        Configuration login_conf = AuthUtils.GetConfiguration(storm_conf);
        // construct a transport plugin
        ITransportPlugin transportPlugin = AuthUtils.GetTransportPlugin(storm_conf, login_conf);
        // create a socket with server
        if (host == null) {
            throw new IllegalArgumentException("host is not set");
        }
        if (port <= 0) {
            throw new IllegalArgumentException("invalid port: " + port);
        }
        //			/***************only test for daily *************/
        //			if (host.endsWith("bja")) {
        //				host += ".tbsite.net";
        //			}
        //			/***************only test for daily *************/
        TSocket socket = new TSocket(host, port);
        if (timeout != null) {
            socket.setTimeout(timeout);
        }
        final TTransport underlyingTransport = socket;
        // establish client-server transport via plugin
        _transport = transportPlugin.connect(underlyingTransport, host);
    } catch (IOException ex) {
        throw new RuntimeException("Create transport error");
    }
    _protocol = null;
    if (_transport != null)
        _protocol = new TBinaryProtocol(_transport);
}
Example 40
Project: tuscany-sca-2.x-master  File: CalculatorClient.java View source code
public static void main(String[] args) throws Exception {
    try {
        Configuration secConf = Configuration.getConfiguration();
    } catch (java.lang.SecurityException e) {
        System.setProperty("java.security.auth.login.config", CalculatorClient.class.getClassLoader().getResource("implementation/policies/CalculatorJass.config").toString());
    }
    NodeFactory factory = NodeFactory.newInstance();
    Node node = factory.createNode(new File("src/main/resources/implementation/policies/ImplementationPolicies.composite").toURI().toURL().toString(), new Contribution("TestContribution", new File("src/main/resources/implementation/policies/").toURI().toURL().toString()));
    node.start();
    CalculatorService calculatorService = node.getService(CalculatorService.class, "CalculatorServiceComponent");
    // Calculate
    System.out.println("Calling CalculatorServiceComponent configured with 'logging' " + "policy for subtract and divide operations...");
    System.out.println("3 + 2=" + calculatorService.add(3, 2));
    System.out.println("3 - 2=" + calculatorService.subtract(3, 2));
    System.out.println("3 * 2=" + calculatorService.multiply(3, 2));
    System.out.println("3 / 2=" + calculatorService.divide(3, 2));
    calculatorService = node.getService(CalculatorService.class, "AnotherCalculatorServiceComponent");
    // Calculate
    System.out.println("Calling CalculatorServiceComponent configured with 'logging' " + "for all operations in the implementation...");
    System.out.println("3 + 2=" + calculatorService.add(3, 2));
    System.out.println("3 - 2=" + calculatorService.subtract(3, 2));
    System.out.println("3 * 2=" + calculatorService.multiply(3, 2));
    System.out.println("3 / 2=" + calculatorService.divide(3, 2));
    node.stop();
    System.out.println("Bye");
}
Example 41
Project: activemq-artemis-master  File: JaasDualAuthenticationBrokerTest.java View source code
/**
    * create a dual login config, for both SSL and non-SSL connections
    * using the StubLoginModule
    */
void createLoginConfig() {
    HashMap<String, String> sslConfigOptions = new HashMap<>();
    HashMap<String, String> configOptions = new HashMap<>();
    sslConfigOptions.put(StubLoginModule.ALLOW_LOGIN_PROPERTY, "true");
    sslConfigOptions.put(StubLoginModule.USERS_PROPERTY, DN_USERNAME);
    sslConfigOptions.put(StubLoginModule.GROUPS_PROPERTY, DN_GROUP);
    AppConfigurationEntry sslConfigEntry = new AppConfigurationEntry("org.apache.activemq.security.StubLoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, sslConfigOptions);
    configOptions.put(StubLoginModule.ALLOW_LOGIN_PROPERTY, "true");
    configOptions.put(StubLoginModule.USERS_PROPERTY, INSECURE_USERNAME);
    configOptions.put(StubLoginModule.GROUPS_PROPERTY, INSECURE_GROUP);
    AppConfigurationEntry configEntry = new AppConfigurationEntry("org.apache.activemq.security.StubLoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, configOptions);
    StubDualJaasConfiguration jaasConfig = new StubDualJaasConfiguration(configEntry, sslConfigEntry);
    Configuration.setConfiguration(jaasConfig);
}
Example 42
Project: cdap-master  File: JAASLoginService.java View source code
/* ------------------------------------------------------------ */
public UserIdentity login(final String username, final Object credentials) {
    try {
        CallbackHandler callbackHandler = null;
        if (callbackHandlerClass == null) {
            callbackHandler = new CallbackHandler() {

                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                    for (Callback callback : callbacks) {
                        if (callback instanceof NameCallback) {
                            ((NameCallback) callback).setName(username);
                        } else if (callback instanceof PasswordCallback) {
                            ((PasswordCallback) callback).setPassword(credentials.toString().toCharArray());
                        } else if (callback instanceof ObjectCallback) {
                            ((ObjectCallback) callback).setObject(credentials);
                        } else if (callback instanceof RequestParameterCallback) {
                            AbstractHttpConnection connection = AbstractHttpConnection.getCurrentConnection();
                            Request request = (connection == null ? null : connection.getRequest());
                            if (request != null) {
                                RequestParameterCallback rpc = (RequestParameterCallback) callback;
                                rpc.setParameterValues(Arrays.asList(request.getParameterValues(rpc.getParameterName())));
                            }
                        } else {
                            throw new UnsupportedCallbackException(callback);
                        }
                    }
                }
            };
        } else {
            Class clazz = Loader.loadClass(getClass(), callbackHandlerClass);
            callbackHandler = (CallbackHandler) clazz.newInstance();
        }
        //set up the login context
        //TODO jaspi requires we provide the Configuration parameter
        Subject subject = new Subject();
        LoginContext loginContext = new LoginContext(loginModuleName, subject, callbackHandler, configuration);
        loginContext.login();
        //login success
        JAASUserPrincipal userPrincipal = new JAASUserPrincipal(getUserName(callbackHandler), subject, loginContext);
        subject.getPrincipals().add(userPrincipal);
        return identityService.newUserIdentity(subject, userPrincipal, getGroups(subject));
    } catch (LoginException e) {
        LOG.debug(e);
    } catch (IOException e) {
        LOG.info(e.getMessage());
        LOG.debug(e);
    } catch (UnsupportedCallbackException e) {
        LOG.info(e.getMessage());
        LOG.debug(e);
    } catch (InstantiationException e) {
        LOG.info(e.getMessage());
        LOG.debug(e);
    } catch (IllegalAccessException e) {
        LOG.info(e.getMessage());
        LOG.debug(e);
    } catch (ClassNotFoundException e) {
        LOG.info(e.getMessage());
        LOG.debug(e);
    }
    return null;
}
Example 43
Project: distributed-processor-master  File: AuthUtils.java View source code
/**
     * Construct a JAAS configuration object per storm configuration file 
     * @param storm_conf Storm configuration 
     * @return JAAS configuration object
     */
public static Configuration GetConfiguration(Map storm_conf) {
    Configuration login_conf = null;
    //find login file configuration from Storm configuration  
    String loginConfigurationFile = (String) storm_conf.get("java.security.auth.login.config");
    if ((loginConfigurationFile != null) && (loginConfigurationFile.length() > 0)) {
        try {
            URI config_uri = new File(loginConfigurationFile).toURI();
            login_conf = Configuration.getInstance("JavaLoginConfig", new URIParameter(config_uri));
        } catch (NoSuchAlgorithmException ex1) {
            if (ex1.getCause() instanceof FileNotFoundException)
                throw new RuntimeException("configuration file " + loginConfigurationFile + " could not be found");
            else
                throw new RuntimeException(ex1);
        } catch (Exception ex2) {
            throw new RuntimeException(ex2);
        }
    }
    return login_conf;
}
Example 44
Project: felix-master  File: ITJaasWithConfigBasedLoginModule.java View source code
@Test
public void testJaasWithTCCL() throws Exception {
    String realmName = name.getMethodName();
    createLoginModuleConfig(realmName);
    delay();
    CallbackHandler handler = new SimpleCallbackHandler("foo", "foo");
    Configuration config = Configuration.getInstance("JavaLoginConfig", null, "FelixJaasProvider");
    Subject s = new Subject();
    final ClassLoader cl = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        LoginContext lc = new LoginContext(realmName, s, handler, config);
        lc.login();
    } finally {
        Thread.currentThread().setContextClassLoader(cl);
    }
    assertFalse(s.getPrincipals().isEmpty());
}
Example 45
Project: mina-sshd-master  File: JaasPasswordAuthenticatorTest.java View source code
@Before
public void setUp() {
    Configuration config = new Configuration() {

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return new AppConfigurationEntry[] { new AppConfigurationEntry(DummyLoginModule.class.getName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap<>()) };
        }

        @Override
        public void refresh() {
        // ignored
        }
    };
    Configuration.setConfiguration(config);
}
Example 46
Project: presto-master  File: KerberosAuthentication.java View source code
private static Configuration createConfiguration(String principal, String keytabLocation) {
    Map<String, String> options = ImmutableMap.<String, String>builder().put("useKeyTab", "true").put("storeKey", "true").put("doNotPrompt", "true").put("isInitiator", "true").put("principal", principal).put("keyTab", keytabLocation).build();
    return new Configuration() {

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return new AppConfigurationEntry[] { new AppConfigurationEntry(KERBEROS_LOGIN_MODULE, AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options) };
        }
    };
}
Example 47
Project: scumd-master  File: JaasPasswordAuthenticatorTest.java View source code
@Before
public void setUp() {
    Configuration config = new Configuration() {

        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return new AppConfigurationEntry[] { new AppConfigurationEntry(DummyLoginModule.class.getName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap<String, Object>()) };
        }

        public void refresh() {
        }
    };
    Configuration.setConfiguration(config);
}
Example 48
Project: spark-svn-mirror-master  File: GSSAPIConfiguration.java View source code
private void init(boolean config_from_file) {
    configs = new HashMap<String, Vector<AppConfigurationEntry>>();
    //The structure of the options is not well documented in terms of
    //data types.  Since the file version of the Configuration object
    //puts things in quotes, String is assumed. But boolean options
    //do not have quotes, and my represent different types internally.
    HashMap<String, String> c_options = new HashMap<String, String>();
    //So don't set refreshKrb5Config
    if (config_from_file) {
        c_options.put("refreshKrb5Config", "true");
    }
    c_options.put("doNotPrompt", "true");
    c_options.put("useTicketCache", "true");
    c_options.put("debug", "true");
    putAppConfigurationEntry("com.sun.security.jgss.initiate", "com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, c_options);
    putAppConfigurationEntry("com.sun.security.jgss.krb5.initiate", "com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, c_options);
}
Example 49
Project: Storm-master  File: AuthUtils.java View source code
/**
     * Construct a JAAS configuration object per storm configuration file 
     * @param storm_conf Storm configuration 
     * @return JAAS configuration object
     */
public static Configuration GetConfiguration(Map storm_conf) {
    Configuration login_conf = null;
    //find login file configuration from Storm configuration  
    String loginConfigurationFile = (String) storm_conf.get("java.security.auth.login.config");
    if ((loginConfigurationFile != null) && (loginConfigurationFile.length() > 0)) {
        try {
            URI config_uri = new File(loginConfigurationFile).toURI();
            login_conf = Configuration.getInstance("JavaLoginConfig", new URIParameter(config_uri));
        } catch (NoSuchAlgorithmException ex1) {
            if (ex1.getCause() instanceof FileNotFoundException)
                throw new RuntimeException("configuration file " + loginConfigurationFile + " could not be found");
            else
                throw new RuntimeException(ex1);
        } catch (Exception ex2) {
            throw new RuntimeException(ex2);
        }
    }
    return login_conf;
}
Example 50
Project: ACaZoo-master  File: ZooKeeperSaslClient.java View source code
public boolean clientTunneledAuthenticationInProgress() {
    // configured to use SASL. (see also ZOOKEEPER-1455).
    try {
        if ((System.getProperty(Environment.JAAS_CONF_KEY) != null) || ((javax.security.auth.login.Configuration.getConfiguration() != null) && (javax.security.auth.login.Configuration.getConfiguration().getAppConfigurationEntry(System.getProperty(ZooKeeperSaslClient.LOGIN_CONTEXT_NAME_KEY, "Client")) != null))) {
            // 1. Authentication hasn't finished yet: we must wait for it to do so.
            if ((isComplete() == false) && (isFailed() == false)) {
                return true;
            }
            // 2. SASL authentication has succeeded or failed..
            if (isComplete() || isFailed()) {
                if (gotLastPacket == false) {
                    // message from server which must be received.
                    return true;
                }
            }
        }
        // not), and all server SASL messages have been received.
        return false;
    } catch (SecurityException e) {
        if (LOG.isDebugEnabled() == true) {
            LOG.debug("Could not retrieve login configuration: " + e);
        }
        return false;
    }
}
Example 51
Project: cxf-master  File: JAASLoginInterceptorTest.java View source code
private JAASLoginInterceptor createTestJaasLoginInterceptor() {
    JAASLoginInterceptor jaasInt = new JAASLoginInterceptor();
    jaasInt.setReportFault(true);
    Configuration config = new Configuration() {

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            Map<String, String> options = new HashMap<>();
            AppConfigurationEntry configEntry = new AppConfigurationEntry(TestUserPasswordLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, options);
            return Collections.singleton(configEntry).toArray(new AppConfigurationEntry[] {});
        }
    };
    jaasInt.setLoginConfig(config);
    return jaasInt;
}
Example 52
Project: hadoop-release-2.6.0-master  File: ZKDelegationTokenSecretManager.java View source code
private String setJaasConfiguration(Configuration config) throws Exception {
    String keytabFile = config.get(ZK_DTSM_ZK_KERBEROS_KEYTAB, "").trim();
    if (keytabFile == null || keytabFile.length() == 0) {
        throw new IllegalArgumentException(ZK_DTSM_ZK_KERBEROS_KEYTAB + " must be specified");
    }
    String principal = config.get(ZK_DTSM_ZK_KERBEROS_PRINCIPAL, "").trim();
    if (principal == null || principal.length() == 0) {
        throw new IllegalArgumentException(ZK_DTSM_ZK_KERBEROS_PRINCIPAL + " must be specified");
    }
    JaasConfiguration jConf = new JaasConfiguration(JAAS_LOGIN_ENTRY_NAME, principal, keytabFile);
    javax.security.auth.login.Configuration.setConfiguration(jConf);
    return principal.split("[/@]")[0];
}
Example 53
Project: zoo-master  File: SaslAuthDesignatedClientTest.java View source code
@Test
public void testSaslConfig() throws Exception {
    ZooKeeper zk = createClient();
    try {
        zk.getChildren("/", false);
        Assert.assertFalse(zk.getSaslClient().clientTunneledAuthenticationInProgress());
        Assert.assertEquals(zk.getSaslClient().getSaslState(), ZooKeeperSaslClient.SaslState.COMPLETE);
        Assert.assertNotNull(javax.security.auth.login.Configuration.getConfiguration().getAppConfigurationEntry("MyZookeeperClient"));
        Assert.assertSame(zk.getSaslClient().getLoginContext(), "MyZookeeperClient");
    } catch (KeeperException e) {
        Assert.fail("test failed :" + e);
    } finally {
        zk.close();
    }
}
Example 54
Project: zookeeper-master  File: SaslAuthDesignatedClientTest.java View source code
@Test
public void testSaslConfig() throws Exception {
    ZooKeeper zk = createClient();
    try {
        zk.getChildren("/", false);
        Assert.assertFalse(zk.getSaslClient().clientTunneledAuthenticationInProgress());
        Assert.assertEquals(zk.getSaslClient().getSaslState(), ZooKeeperSaslClient.SaslState.COMPLETE);
        Assert.assertNotNull(javax.security.auth.login.Configuration.getConfiguration().getAppConfigurationEntry("MyZookeeperClient"));
        Assert.assertSame(zk.getSaslClient().getLoginContext(), "MyZookeeperClient");
    } catch (KeeperException e) {
        Assert.fail("test failed :" + e);
    } finally {
        zk.close();
    }
}
Example 55
Project: tomee-master  File: Main.java View source code
@Override
protected javax.security.auth.login.Configuration getConfig() {
    try {
        if (jaasConfigurationLoaded) {
            return jaasConfiguration;
        }
        synchronized (this) {
            if (configFile == null) {
                jaasConfigurationLoaded = true;
                return null;
            }
            configFile = file.getAbsolutePath();
            final Class<?> sunConfigFile = Class.forName("com.sun.security.auth.login.ConfigFile");
            final Constructor<?> constructor = sunConfigFile.getConstructor(URI.class);
            javax.security.auth.login.Configuration config = javax.security.auth.login.Configuration.class.cast(constructor.newInstance(file.toURI()));
            this.jaasConfiguration = config;
            this.jaasConfigurationLoaded = true;
            return this.jaasConfiguration;
        }
    } catch (final NoSuchMethodExceptionSecurityException | IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException | ClassNotFoundException |  ex) {
        throw new RuntimeException(ex);
    }
}
Example 56
Project: activemq-master  File: JaasDualAuthenticationBrokerTest.java View source code
/** create a dual login config, for both SSL and non-SSL connections
     * using the StubLoginModule
     *
     */
void createLoginConfig() {
    HashMap<String, String> sslConfigOptions = new HashMap<String, String>();
    HashMap<String, String> configOptions = new HashMap<String, String>();
    sslConfigOptions.put(StubLoginModule.ALLOW_LOGIN_PROPERTY, "true");
    sslConfigOptions.put(StubLoginModule.USERS_PROPERTY, DN_USERNAME);
    sslConfigOptions.put(StubLoginModule.GROUPS_PROPERTY, DN_GROUP);
    AppConfigurationEntry sslConfigEntry = new AppConfigurationEntry("org.apache.activemq.security.StubLoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, sslConfigOptions);
    configOptions.put(StubLoginModule.ALLOW_LOGIN_PROPERTY, "true");
    configOptions.put(StubLoginModule.USERS_PROPERTY, INSECURE_USERNAME);
    configOptions.put(StubLoginModule.GROUPS_PROPERTY, INSECURE_GROUP);
    AppConfigurationEntry configEntry = new AppConfigurationEntry("org.apache.activemq.security.StubLoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, configOptions);
    StubDualJaasConfiguration jaasConfig = new StubDualJaasConfiguration(configEntry, sslConfigEntry);
    Configuration.setConfiguration(jaasConfig);
}
Example 57
Project: bookkeeper-master  File: EnableZkSecurityBasicTest.java View source code
@BeforeClass
public static void setupJAAS() throws IOException {
    System.setProperty("zookeeper.authProvider.1", "org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
    File tmpJaasDir = new File("target").getAbsoluteFile();
    File tmpJaasFile = new File(tmpJaasDir, "jaas.conf");
    String jassFileContent = "Server {\n" + "       org.apache.zookeeper.server.auth.DigestLoginModule required\n" + "       user_foo=\"bar\";\n" + "};\n" + "\n" + "Client {\n" + "       org.apache.zookeeper.server.auth.DigestLoginModule required\n" + "       username=\"foo\"\n" + "       password=\"bar\";\n" + "};";
    Files.write(tmpJaasFile.toPath(), jassFileContent.getBytes(StandardCharsets.UTF_8));
    System.setProperty("java.security.auth.login.config", tmpJaasFile.getAbsolutePath());
    Configuration.getConfiguration().refresh();
}
Example 58
Project: directory-server-master  File: SaslGssapiBindITest.java View source code
/**
     * Tests to make sure GSSAPI binds below the RootDSE work.
     */
@Test
public void testSaslGssapiBind() throws Exception {
    // Set up a partition for EXAMPLE.COM and add user and service principals to test authentication with.
    KerberosTestUtils.fixServicePrincipalName("ldap/" + KerberosTestUtils.getHostName() + "@EXAMPLE.COM", null, getLdapServer());
    ObtainTicketParameters parameters = new ObtainTicketParameters(TcpTransport.class, EncryptionType.AES128_CTS_HMAC_SHA1_96, ChecksumType.HMAC_SHA1_96_AES128);
    setupEnv(parameters);
    kdcServer.getConfig().setPaEncTimestampRequired(false);
    // Use our custom configuration to avoid reliance on external config
    Configuration.setConfiguration(new Krb5LoginConfiguration());
    // 1. Authenticate to Kerberos.
    LoginContext lc = null;
    try {
        lc = new LoginContext(SaslGssapiBindITest.class.getName(), new CallbackHandlerBean("hnelson", "secret"));
        lc.login();
    } catch (LoginException le) {
        fail("Authentication failed:  " + le.getMessage());
    }
    // 2. Perform JNDI work as authenticated Subject.
    Subject.doAs(lc.getSubject(), new PrivilegedAction<Void>() {

        public Void run() {
            //Currently GSSAPI authentication for the ldap server is broken
            try {
                // Create the initial context
                Hashtable<String, String> env = new Hashtable<String, String>();
                env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
                env.put(Context.PROVIDER_URL, "ldap://" + KerberosTestUtils.getHostName() + ":" + getLdapServer().getPort());
                // Request the use of the "GSSAPI" SASL mechanism
                // Authenticate by using already established Kerberos credentials
                env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
                // Request privacy protection
                env.put("javax.security.sasl.qop", "auth-conf");
                // Request mutual authentication
                env.put("javax.security.sasl.server.authentication", "true");
                // Request high-strength cryptographic protection
                env.put("javax.security.sasl.strength", "high");
                DirContext ctx = new InitialDirContext(env);
                String[] attrIDs = { "uid" };
                Attributes attrs = ctx.getAttributes("uid=hnelson,ou=users,dc=example,dc=com", attrIDs);
                String uid = null;
                if (attrs.get("uid") != null) {
                    uid = (String) attrs.get("uid").get();
                }
                assertEquals(uid, "hnelson");
            } catch (NamingException e) {
                fail("Should not have caught exception:  " + e.getMessage() + e.getRootCause());
            }
            return null;
        }
    });
}
Example 59
Project: federation-master  File: SAMLRoleLoginModuleUnitTestCase.java View source code
@Before
public void setup() {
    Configuration.setConfiguration(new Configuration() {

        @SuppressWarnings({ "rawtypes", "unchecked" })
        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            final Map options = new HashMap();
            AppConfigurationEntry a1 = new AppConfigurationEntry(MySAMLModule.class.getName(), LoginModuleControlFlag.REQUIRED, options);
            AppConfigurationEntry a2 = new AppConfigurationEntry(SAMLRoleLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, options);
            return new AppConfigurationEntry[] { a1, a2 };
        }
    });
}
Example 60
Project: geronimo-master  File: SubjectCarryingProtocolTest.java View source code
public void tearDown() throws Exception {
    server.dispose();
    kernel.stopGBean(testRealm);
    kernel.stopGBean(testCE);
    kernel.stopGBean(serverInfo);
    kernel.unloadGBean(testCE);
    kernel.unloadGBean(testRealm);
    kernel.unloadGBean(serverInfo);
    super.tearDown();
    Configuration.setConfiguration(new ConfigFile());
}
Example 61
Project: jackrabbit-master  File: AuthContextProvider.java View source code
/**
     *
     * @param credentials
     * @param subject
     * @param session
     * @param principalProviderRegistry
     * @param adminId
     * @param anonymousId
     * @return context of for authentication and log-out
     * @throws RepositoryException in case neither an <code>JAASContext</code>
     * nor a <code>LocalContext</code> can be successfully created.
     */
public AuthContext getAuthContext(Credentials credentials, Subject subject, Session session, PrincipalProviderRegistry principalProviderRegistry, String adminId, String anonymousId) throws RepositoryException {
    CallbackHandler cbHandler = new CallbackHandlerImpl(credentials, session, principalProviderRegistry, adminId, anonymousId);
    if (isLocal()) {
        return new LocalAuthContext(config, cbHandler, subject);
    } else if (isJAAS()) {
        return new JAASAuthContext(appName, cbHandler, subject);
    } else {
        throw new RepositoryException("No Login-Configuration");
    }
}
Example 62
Project: ldaptive-master  File: ApacheLdapSaslUtils.java View source code
/**
   * Creates a new gssapi request.
   *
   * @param  username  to bind as
   * @param  credential  to bind with
   * @param  config  to set sasl parameters
   *
   * @return  gssapi request
   */
protected static SaslGssApiRequest createGssApiRequest(final String username, final Credential credential, final SaslConfig config) {
    final SaslGssApiRequest request = new SaslGssApiRequest();
    if (username != null) {
        request.setUsername(username);
    }
    if (credential != null) {
        request.setCredentials(credential.getBytes());
    }
    if (config.getAuthorizationId() != null) {
        request.setAuthorizationId(config.getAuthorizationId());
    }
    if (config.getMutualAuthentication() != null) {
        request.setMutualAuthentication(config.getMutualAuthentication());
    }
    if (config.getQualityOfProtection() != null) {
        request.setQualityOfProtection(getQualityOfProtection(config.getQualityOfProtection()));
    }
    if (config.getSecurityStrength() != null) {
        request.setSecurityStrength(getSecurityStrength(config.getSecurityStrength()));
    }
    if (config instanceof GssApiConfig) {
        final GssApiConfig c = (GssApiConfig) config;
        if (c.getRealm() != null) {
            request.setRealmName(c.getRealm());
        }
    }
    final String realm = System.getProperty("java.security.krb5.realm");
    if (realm != null) {
        request.setRealmName(realm);
    }
    final String kdcHost = System.getProperty("java.security.krb5.kdc");
    if (kdcHost != null) {
        request.setKdcHost(kdcHost);
    }
    final String loginConfig = System.getProperty("java.security.auth.login.config");
    if (loginConfig != null) {
        request.setLoginModuleConfiguration(Configuration.getConfiguration());
    }
    request.setLoginContextName("com.sun.security.jgss.initiate");
    return request;
}
Example 63
Project: mymam-master  File: JBossLoginContextFactory.java View source code
/**
     * Obtain a LoginContext configured for use with the ClientLoginModule.
     *
     * @return the configured LoginContext.
     */
public static LoginContext createLoginContext(final String username, final String password) throws LoginException {
    final String configurationName = "Arquillian Testing";
    CallbackHandler cbh = new JBossLoginContextFactory.NamePasswordCallbackHandler(username, password);
    Configuration config = new JBossJaasConfiguration(configurationName);
    return new LoginContext(configurationName, new Subject(), cbh, config);
}
Example 64
Project: picketlink-bindings-master  File: SAMLRoleLoginModuleUnitTestCase.java View source code
@Before
public void setup() {
    Configuration.setConfiguration(new Configuration() {

        @SuppressWarnings({ "rawtypes", "unchecked" })
        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            final Map options = new HashMap();
            AppConfigurationEntry a1 = new AppConfigurationEntry(MySAMLModule.class.getName(), LoginModuleControlFlag.REQUIRED, options);
            AppConfigurationEntry a2 = new AppConfigurationEntry(SAMLRoleLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, options);
            return new AppConfigurationEntry[] { a1, a2 };
        }
    });
}
Example 65
Project: rj-core-master  File: JaasAuthMethod.java View source code
@Override
public void doInit(final String arg) throws RjException {
    this.configuration = Configuration.getConfiguration();
    if (this.configuration.getAppConfigurationEntry(JAAS_NAME) == null) {
        this.configuration = new JaasConfig(arg);
    }
    try {
        this.context = new LoginContext(JAAS_NAME, new Subject(), this, this.configuration);
    } catch (final LoginException e) {
        e.printStackTrace();
    }
}
Example 66
Project: schema-registry-master  File: SASLClusterTestHarness.java View source code
@Before
@Override
public void setUp() throws Exception {
    // Important if tests leak consumers, producers or brokers.
    LoginManager.closeAll();
    File serverKeytab = File.createTempFile("server-", ".keytab");
    File clientKeytab = File.createTempFile("client-", ".keytab");
    // create a JAAS file.
    Option<File> serverKeytabOption = Option.apply(serverKeytab);
    Option<File> clientKeytabOption = Option.apply(clientKeytab);
    List<String> serverSaslMechanisms = JavaConversions.asScalaBuffer(Arrays.asList("GSSAPI")).toList();
    Option<String> clientSaslMechanism = Option.apply("GSSAPI");
    java.util.List<JaasTestUtils.JaasSection> jaasSections = new ArrayList<>();
    jaasSections.add(JaasTestUtils.kafkaServerSection(JaasTestUtils.KafkaServerContextName(), serverSaslMechanisms, serverKeytabOption));
    jaasSections.add(JaasTestUtils.kafkaClientSection(clientSaslMechanism, clientKeytabOption));
    jaasSections.addAll(JavaConversions.asJavaCollection(JaasTestUtils.zkSections()));
    String jaasFilePath = JaasTestUtils.writeJaasContextsToFile(JavaConversions.asScalaBuffer(jaasSections).toSeq()).getAbsolutePath();
    log.info("Using KDC home: " + kdcHome.getAbsolutePath());
    kdc = new MiniKdc(kdcProps, kdcHome);
    kdc.start();
    createPrincipal(serverKeytab, "kafka/localhost");
    createPrincipal(clientKeytab, "client");
    createPrincipal(clientKeytab, "client2");
    // This will cause a reload of the Configuration singleton when `getConfiguration` is called.
    Configuration.setConfiguration(null);
    System.setProperty(JAAS_CONF, jaasFilePath);
    System.setProperty(ZK_AUTH_PROVIDER, "org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
    super.setUp();
}
Example 67
Project: simba-os-master  File: JaasLoginCommandTest.java View source code
private void setupJAAS() {
    Configuration configurationMock = mock(Configuration.class);
    AppConfigurationEntry entry = new AppConfigurationEntry(TestLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, Collections.<String, Object>emptyMap());
    when(configurationMock.getAppConfigurationEntry(LOGIN_MODULE_NAME)).thenReturn(new AppConfigurationEntry[] { entry });
    Configuration.setConfiguration(configurationMock);
}
Example 68
Project: sling-master  File: DelegatingLoginModule.java View source code
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) {
    Configuration config = null;
    try {
        config = Configuration.getInstance(JAAS_CONFIG_ALGO_NAME, null, providerName);
    } catch (NoSuchProviderException e) {
        logger.debug("No provider " + providerName + "found so far", e);
    } catch (NoSuchAlgorithmException e) {
        logger.debug("No provider " + providerName + "found so far for fetching JAAS " + "config with algorithm name " + JAAS_CONFIG_ALGO_NAME, e);
    }
    if (config != null) {
        final Thread current = Thread.currentThread();
        final ClassLoader orig = current.getContextClassLoader();
        try {
            current.setContextClassLoader(DelegatingLoginModule.class.getClassLoader());
            loginContext = new LoginContext(appName, subject, callbackHandler, config);
        } catch (LoginException e) {
            loginException = e;
        } finally {
            current.setContextClassLoader(orig);
        }
    } else {
        //No support so far from OSGi so would use default logic used by Jackrabbit
        //to construct the LoginModule
        Properties p = new Properties();
        p.putAll(options);
        BeanConfig bc = new BeanConfig(delegateLoginModuleClass, p);
        LoginModuleConfig lmc = new LoginModuleConfig(bc);
        try {
            delegate = lmc.getLoginModule();
            delegate.initialize(subject, callbackHandler, sharedState, options);
            logger.info("No JAAS Configuration provider found would be directly invoking LoginModule {}", delegateLoginModuleClass);
        } catch (ConfigurationException e) {
            loginException = new LoginException(e.getMessage());
        }
    }
}
Example 69
Project: storm-solr-master  File: FusionKrb5HttpClientConfigurer.java View source code
public void configure(DefaultHttpClient httpClient, SolrParams config) {
    super.configure(httpClient, config);
    if (System.getProperty(LOGIN_CONFIG_PROP) != null) {
        String configValue = System.getProperty(LOGIN_CONFIG_PROP);
        if (configValue != null) {
            logger.debug("Setting up kerberos auth with config: " + configValue);
            System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
            if (fusionPrincipal != null) {
                Subject subject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(fusionPrincipal)), Collections.emptySet(), Collections.emptySet());
                LoginContext loginContext;
                try {
                    loginContext = new LoginContext("", subject, null, jaasConfig);
                    loginContext.login();
                    logger.debug("Successful Fusion Login with principal: " + fusionPrincipal);
                } catch (LoginException e) {
                    String errorMessage = "Unsuccessful Fusion Login with principal: " + fusionPrincipal;
                    logger.error(errorMessage, e);
                    throw new RuntimeException(errorMessage, e);
                }
            }
            Configuration.setConfiguration(jaasConfig);
            httpClient.getAuthSchemes().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, false));
            Credentials useJaasCreds = new Credentials() {

                public String getPassword() {
                    return null;
                }

                public Principal getUserPrincipal() {
                    return null;
                }
            };
            httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, useJaasCreds);
            httpClient.addRequestInterceptor(this.bufferedEntityInterceptor);
        } else {
            httpClient.getCredentialsProvider().clear();
        }
    }
}
Example 70
Project: wildfly-camel-master  File: LoginContextBuilder.java View source code
// Provides a RunAs client login context
private LoginContext getClientLoginContext() throws LoginException {
    Configuration config = new Configuration() {

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            Map<String, String> options = new HashMap<String, String>();
            options.put("multi-threaded", "true");
            options.put("restore-login-identity", "true");
            AppConfigurationEntry clmEntry = new AppConfigurationEntry(ClientLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, options);
            return new AppConfigurationEntry[] { clmEntry };
        }
    };
    return getLoginContext(config);
}
Example 71
Project: wildfly-core-master  File: KeytabService.java View source code
private Configuration createConfiguration(final boolean isServer, final File keyTabFile) throws MalformedURLException {
    Map<String, Object> options = new HashMap<String, Object>();
    if (debug) {
        options.put("debug", "true");
    }
    options.put("principal", principal);
    final AppConfigurationEntry ace;
    if (IS_IBM) {
        options.put("noAddress", "true");
        options.put("credsType", isServer ? "acceptor" : "initiator");
        options.put("useKeytab", keyTabFile.toURI().toURL().toString());
        ace = new AppConfigurationEntry(IBMKRB5LoginModule, REQUIRED, options);
    } else {
        options.put("storeKey", "true");
        options.put("useKeyTab", "true");
        options.put("keyTab", keyTabFile.getAbsolutePath());
        options.put("isInitiator", isServer ? "false" : "true");
        ace = new AppConfigurationEntry(KRB5LoginModule, REQUIRED, options);
    }
    final AppConfigurationEntry[] aceArray = new AppConfigurationEntry[] { ace };
    return new Configuration() {

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            assert "KDC".equals(name);
            return aceArray;
        }
    };
}
Example 72
Project: hbase-master  File: DemoClient.java View source code
public static void main(String[] args) throws Exception {
    System.out.println("Thrift2 Demo");
    System.out.println("Usage: DemoClient [host=localhost] [port=9090] [secure=false]");
    System.out.println("This demo assumes you have a table called \"example\" with a column family called \"family1\"");
    // use passed in arguments instead of defaults
    if (args.length >= 1) {
        host = args[0];
    }
    if (args.length >= 2) {
        port = Integer.parseInt(args[1]);
    }
    org.apache.hadoop.conf.Configuration conf = HBaseConfiguration.create();
    String principal = conf.get("hbase.thrift.kerberos.principal");
    if (principal != null) {
        secure = true;
        int slashIdx = principal.indexOf("/");
        int atIdx = principal.indexOf("@");
        int idx = slashIdx != -1 ? slashIdx : atIdx != -1 ? atIdx : principal.length();
        user = principal.substring(0, idx);
    }
    if (args.length >= 3) {
        secure = Boolean.parseBoolean(args[2]);
    }
    final DemoClient client = new DemoClient();
    Subject.doAs(getSubject(), new PrivilegedExceptionAction<Void>() {

        @Override
        public Void run() throws Exception {
            client.run();
            return null;
        }
    });
}
Example 73
Project: ranger-master  File: SolrAuditDestination.java View source code
private void resetInitializerInSOLR() {
    javax.security.auth.login.Configuration solrConfig = javax.security.auth.login.Configuration.getConfiguration();
    String solrConfigClassName = solrConfig.getClass().getName();
    String solrJassConfigEnd = "SolrJaasConfiguration";
    if (solrConfigClassName.endsWith(solrJassConfigEnd)) {
        try {
            Field f = solrConfig.getClass().getDeclaredField("initiateAppNames");
            if (f != null) {
                f.setAccessible(true);
                HashSet<String> val = new HashSet<String>();
                f.set(solrConfig, val);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("resetInitializerInSOLR: successfully reset the initiateAppNames");
                }
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("resetInitializerInSOLR: not applying on class [" + solrConfigClassName + "] as it does not have initiateAppNames variable name.");
                }
            }
        } catch (Throwable t) {
            logError("resetInitializerInSOLR: Unable to reset SOLRCONFIG.initiateAppNames to be empty", t);
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("resetInitializerInSOLR: not applying on class [" + solrConfigClassName + "] as it does not endwith [" + solrJassConfigEnd + "]");
        }
    }
}
Example 74
Project: spring-security-master  File: JaasApiIntegrationFilterTests.java View source code
// ~ Methods
// ========================================================================================================
@Before
public void onBeforeTests() throws Exception {
    this.filter = new JaasApiIntegrationFilter();
    this.request = new MockHttpServletRequest();
    this.response = new MockHttpServletResponse();
    authenticatedSubject = new Subject();
    authenticatedSubject.getPrincipals().add(new Principal() {

        public String getName() {
            return "principal";
        }
    });
    authenticatedSubject.getPrivateCredentials().add("password");
    authenticatedSubject.getPublicCredentials().add("username");
    callbackHandler = new CallbackHandler() {

        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback callback : callbacks) {
                if (callback instanceof NameCallback) {
                    ((NameCallback) callback).setName("user");
                } else if (callback instanceof PasswordCallback) {
                    ((PasswordCallback) callback).setPassword("password".toCharArray());
                } else if (callback instanceof TextInputCallback) {
                // ignore
                } else {
                    throw new UnsupportedCallbackException(callback, "Unrecognized Callback " + callback);
                }
            }
        }
    };
    testConfiguration = new Configuration() {

        public void refresh() {
        }

        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return new AppConfigurationEntry[] { new AppConfigurationEntry(TestLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, new HashMap<String, String>()) };
        }
    };
    LoginContext ctx = new LoginContext("SubjectDoAsFilterTest", authenticatedSubject, callbackHandler, testConfiguration);
    ctx.login();
    token = new JaasAuthenticationToken("username", "password", AuthorityUtils.createAuthorityList("ROLE_ADMIN"), ctx);
    // just in case someone forgot to clear the context
    SecurityContextHolder.clearContext();
}
Example 75
Project: classlib6-master  File: ConfigFile.java View source code
/**
     * Read and initialize the entire login Configuration.
     *
     * <p>
     *
     * @exception IOException if the Configuration can not be initialized. <p>
     * @exception SecurityException if the caller does not have permission
     *				to initialize the Configuration.
     */
private void init(URL url) throws IOException {
    boolean initialized = false;
    FileReader fr = null;
    String sep = File.separator;
    if ("false".equals(System.getProperty("policy.expandProperties"))) {
        expandProp = false;
    }
    // new configuration
    HashMap<String, LinkedList<AppConfigurationEntry>> newConfig = new HashMap<String, LinkedList<AppConfigurationEntry>>();
    if (url != null) {
        /**
	     * If the caller specified a URI via Configuration.getInstance,
	     * we only read from that URI
	     */
        if (debugConfig != null) {
            debugConfig.println("reading " + url);
        }
        init(url, newConfig);
        configuration = newConfig;
        return;
    }
    /**
	 * Caller did not specify URI via Configuration.getInstance.
	 * Read from URLs listed in the java.security properties file.
	 */
    String allowSys = java.security.Security.getProperty("policy.allowSystemProperty");
    if ("true".equalsIgnoreCase(allowSys)) {
        String extra_config = System.getProperty("java.security.auth.login.config");
        if (extra_config != null) {
            boolean overrideAll = false;
            if (extra_config.startsWith("=")) {
                overrideAll = true;
                extra_config = extra_config.substring(1);
            }
            try {
                extra_config = PropertyExpander.expand(extra_config);
            } catch (PropertyExpander.ExpandException peee) {
                MessageFormat form = new MessageFormat(ResourcesMgr.getString("Unable to properly expand config", "sun.security.util.AuthResources"));
                Object[] source = { extra_config };
                throw new IOException(form.format(source));
            }
            URL configURL = null;
            try {
                configURL = new URL(extra_config);
            } catch (java.net.MalformedURLException mue) {
                File configFile = new File(extra_config);
                if (configFile.exists()) {
                    configURL = configFile.toURI().toURL();
                } else {
                    MessageFormat form = new MessageFormat(ResourcesMgr.getString("extra_config (No such file or directory)", "sun.security.util.AuthResources"));
                    Object[] source = { extra_config };
                    throw new IOException(form.format(source));
                }
            }
            if (debugConfig != null) {
                debugConfig.println("reading " + configURL);
            }
            init(configURL, newConfig);
            initialized = true;
            if (overrideAll) {
                if (debugConfig != null) {
                    debugConfig.println("overriding other policies!");
                }
                configuration = newConfig;
                return;
            }
        }
    }
    int n = 1;
    String config_url;
    while ((config_url = java.security.Security.getProperty("login.config.url." + n)) != null) {
        try {
            config_url = PropertyExpander.expand(config_url).replace(File.separatorChar, '/');
            if (debugConfig != null) {
                debugConfig.println("\tReading config: " + config_url);
            }
            init(new URL(config_url), newConfig);
            initialized = true;
        } catch (PropertyExpander.ExpandException peee) {
            MessageFormat form = new MessageFormat(ResourcesMgr.getString("Unable to properly expand config", "sun.security.util.AuthResources"));
            Object[] source = { config_url };
            throw new IOException(form.format(source));
        }
        n++;
    }
    if (initialized == false && n == 1 && config_url == null) {
        // get the config from the user's home directory
        if (debugConfig != null) {
            debugConfig.println("\tReading Policy " + "from ~/.java.login.config");
        }
        config_url = System.getProperty("user.home");
        String userConfigFile = config_url + File.separatorChar + ".java.login.config";
        // at all. Returns an empty Configuration instead.
        if (new File(userConfigFile).exists()) {
            init(new File(userConfigFile).toURI().toURL(), newConfig);
        }
    }
    configuration = newConfig;
}
Example 76
Project: ikvm-openjdk-master  File: ConfigFile.java View source code
/**
     * Read and initialize the entire login Configuration.
     *
     * <p>
     *
     * @exception IOException if the Configuration can not be initialized. <p>
     * @exception SecurityException if the caller does not have permission
     *                          to initialize the Configuration.
     */
private void init(URL url) throws IOException {
    boolean initialized = false;
    FileReader fr = null;
    String sep = File.separator;
    if ("false".equals(System.getProperty("policy.expandProperties"))) {
        expandProp = false;
    }
    // new configuration
    HashMap<String, LinkedList<AppConfigurationEntry>> newConfig = new HashMap<String, LinkedList<AppConfigurationEntry>>();
    if (url != null) {
        /**
             * If the caller specified a URI via Configuration.getInstance,
             * we only read from that URI
             */
        if (debugConfig != null) {
            debugConfig.println("reading " + url);
        }
        init(url, newConfig);
        configuration = newConfig;
        return;
    }
    /**
         * Caller did not specify URI via Configuration.getInstance.
         * Read from URLs listed in the java.security properties file.
         */
    String allowSys = java.security.Security.getProperty("policy.allowSystemProperty");
    if ("true".equalsIgnoreCase(allowSys)) {
        String extra_config = System.getProperty("java.security.auth.login.config");
        if (extra_config != null) {
            boolean overrideAll = false;
            if (extra_config.startsWith("=")) {
                overrideAll = true;
                extra_config = extra_config.substring(1);
            }
            try {
                extra_config = PropertyExpander.expand(extra_config);
            } catch (PropertyExpander.ExpandException peee) {
                MessageFormat form = new MessageFormat(ResourcesMgr.getString("Unable to properly expand config", "sun.security.util.AuthResources"));
                Object[] source = { extra_config };
                throw new IOException(form.format(source));
            }
            URL configURL = null;
            try {
                configURL = new URL(extra_config);
            } catch (java.net.MalformedURLException mue) {
                File configFile = new File(extra_config);
                if (configFile.exists()) {
                    configURL = configFile.toURI().toURL();
                } else {
                    MessageFormat form = new MessageFormat(ResourcesMgr.getString("extra_config (No such file or directory)", "sun.security.util.AuthResources"));
                    Object[] source = { extra_config };
                    throw new IOException(form.format(source));
                }
            }
            if (debugConfig != null) {
                debugConfig.println("reading " + configURL);
            }
            init(configURL, newConfig);
            initialized = true;
            if (overrideAll) {
                if (debugConfig != null) {
                    debugConfig.println("overriding other policies!");
                }
                configuration = newConfig;
                return;
            }
        }
    }
    int n = 1;
    String config_url;
    while ((config_url = java.security.Security.getProperty("login.config.url." + n)) != null) {
        try {
            config_url = PropertyExpander.expand(config_url).replace(File.separatorChar, '/');
            if (debugConfig != null) {
                debugConfig.println("\tReading config: " + config_url);
            }
            init(new URL(config_url), newConfig);
            initialized = true;
        } catch (PropertyExpander.ExpandException peee) {
            MessageFormat form = new MessageFormat(ResourcesMgr.getString("Unable to properly expand config", "sun.security.util.AuthResources"));
            Object[] source = { config_url };
            throw new IOException(form.format(source));
        }
        n++;
    }
    if (initialized == false && n == 1 && config_url == null) {
        // get the config from the user's home directory
        if (debugConfig != null) {
            debugConfig.println("\tReading Policy " + "from ~/.java.login.config");
        }
        config_url = System.getProperty("user.home");
        String userConfigFile = config_url + File.separatorChar + ".java.login.config";
        // at all. Returns an empty Configuration instead.
        if (new File(userConfigFile).exists()) {
            init(new File(userConfigFile).toURI().toURL(), newConfig);
        }
    }
    configuration = newConfig;
}
Example 77
Project: JDK-master  File: ConfigFile.java View source code
/**
     * Read and initialize the entire login Configuration.
     *
     * <p>
     *
     * @exception IOException if the Configuration can not be initialized. <p>
     * @exception SecurityException if the caller does not have permission
     *                          to initialize the Configuration.
     */
private void init(URL url) throws IOException {
    boolean initialized = false;
    FileReader fr = null;
    String sep = File.separator;
    if ("false".equals(System.getProperty("policy.expandProperties"))) {
        expandProp = false;
    }
    // new configuration
    HashMap<String, LinkedList<AppConfigurationEntry>> newConfig = new HashMap<>();
    if (url != null) {
        /**
             * If the caller specified a URI via Configuration.getInstance,
             * we only read from that URI
             */
        if (debugConfig != null) {
            debugConfig.println("reading " + url);
        }
        init(url, newConfig);
        configuration = newConfig;
        return;
    }
    /**
         * Caller did not specify URI via Configuration.getInstance.
         * Read from URLs listed in the java.security properties file.
         */
    String allowSys = java.security.Security.getProperty("policy.allowSystemProperty");
    if ("true".equalsIgnoreCase(allowSys)) {
        String extra_config = System.getProperty("java.security.auth.login.config");
        if (extra_config != null) {
            boolean overrideAll = false;
            if (extra_config.startsWith("=")) {
                overrideAll = true;
                extra_config = extra_config.substring(1);
            }
            try {
                extra_config = PropertyExpander.expand(extra_config);
            } catch (PropertyExpander.ExpandException peee) {
                MessageFormat form = new MessageFormat(ResourcesMgr.getString("Unable.to.properly.expand.config", "sun.security.util.AuthResources"));
                Object[] source = { extra_config };
                throw new IOException(form.format(source));
            }
            URL configURL = null;
            try {
                configURL = new URL(extra_config);
            } catch (java.net.MalformedURLException mue) {
                File configFile = new File(extra_config);
                if (configFile.exists()) {
                    configURL = configFile.toURI().toURL();
                } else {
                    MessageFormat form = new MessageFormat(ResourcesMgr.getString("extra.config.No.such.file.or.directory.", "sun.security.util.AuthResources"));
                    Object[] source = { extra_config };
                    throw new IOException(form.format(source));
                }
            }
            if (debugConfig != null) {
                debugConfig.println("reading " + configURL);
            }
            init(configURL, newConfig);
            initialized = true;
            if (overrideAll) {
                if (debugConfig != null) {
                    debugConfig.println("overriding other policies!");
                }
                configuration = newConfig;
                return;
            }
        }
    }
    int n = 1;
    String config_url;
    while ((config_url = java.security.Security.getProperty("login.config.url." + n)) != null) {
        try {
            config_url = PropertyExpander.expand(config_url).replace(File.separatorChar, '/');
            if (debugConfig != null) {
                debugConfig.println("\tReading config: " + config_url);
            }
            init(new URL(config_url), newConfig);
            initialized = true;
        } catch (PropertyExpander.ExpandException peee) {
            MessageFormat form = new MessageFormat(ResourcesMgr.getString("Unable.to.properly.expand.config", "sun.security.util.AuthResources"));
            Object[] source = { config_url };
            throw new IOException(form.format(source));
        }
        n++;
    }
    if (initialized == false && n == 1 && config_url == null) {
        // get the config from the user's home directory
        if (debugConfig != null) {
            debugConfig.println("\tReading Policy " + "from ~/.java.login.config");
        }
        config_url = System.getProperty("user.home");
        String userConfigFile = config_url + File.separatorChar + ".java.login.config";
        // at all. Returns an empty Configuration instead.
        if (new File(userConfigFile).exists()) {
            init(new File(userConfigFile).toURI().toURL(), newConfig);
        }
    }
    configuration = newConfig;
}
Example 78
Project: tomcat60-master  File: JreMemoryLeakPreventionListener.java View source code
public void lifecycleEvent(LifecycleEvent event) {
    // Initialise these classes when Tomcat starts
    if (Lifecycle.INIT_EVENT.equals(event.getType())) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try {
            // Use the system classloader as the victim for all this
            // ClassLoader pinning we're about to do.
            Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
            /*
                 * First call to this loads all drivers in the current class
                 * loader
                 */
            if (driverManagerProtection) {
                DriverManager.getDrivers();
            }
            // be an issue.
            if (appContextProtection) {
                ImageIO.getCacheDirectory();
            }
            // etc.) thread
            if (awtThreadProtection) {
                java.awt.Toolkit.getDefaultToolkit();
            }
            /*
                 * Several components end up calling
                 * sun.misc.GC.requestLatency(long) which creates a daemon
                 * thread without setting the TCCL.
                 * 
                 * Those libraries / components known to trigger memory leaks
                 * due to eventual calls to requestLatency(long) are:
                 * - javax.management.remote.rmi.RMIConnectorServer.start()
                 *
                 * Note: Long.MAX_VALUE is a special case that causes the thread
                 *       to terminate
                 *
                 */
            if (gcDaemonProtection) {
                try {
                    Class<?> clazz = Class.forName("sun.misc.GC");
                    Method method = clazz.getDeclaredMethod("requestLatency", new Class[] { long.class });
                    method.invoke(null, Long.valueOf(Long.MAX_VALUE - 1));
                } catch (ClassNotFoundException e) {
                    if (System.getProperty("java.vendor").startsWith("Sun")) {
                        log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
                    } else {
                        log.debug(sm.getString("jreLeakListener.gcDaemonFail"), e);
                    }
                } catch (SecurityException e) {
                    log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
                } catch (NoSuchMethodException e) {
                    log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
                } catch (IllegalArgumentException e) {
                    log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
                } catch (IllegalAccessException e) {
                    log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
                } catch (InvocationTargetException e) {
                    log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
                }
            }
            /*
                 * Calling getPolicy retains a static reference to the context 
                 * class loader.
                 */
            if (securityPolicyProtection) {
                try {
                    // Policy.getPolicy();
                    Class<?> policyClass = Class.forName("javax.security.auth.Policy");
                    Method method = policyClass.getMethod("getPolicy");
                    method.invoke(null);
                } catch (ClassNotFoundException e) {
                } catch (SecurityException e) {
                } catch (NoSuchMethodException e) {
                    log.warn(sm.getString("jreLeakListener.authPolicyFail"), e);
                } catch (IllegalArgumentException e) {
                    log.warn(sm.getString("jreLeakListener.authPolicyFail"), e);
                } catch (IllegalAccessException e) {
                    log.warn(sm.getString("jreLeakListener.authPolicyFail"), e);
                } catch (InvocationTargetException e) {
                    log.warn(sm.getString("jreLeakListener.authPolicyFail"), e);
                }
            }
            /*
                 * Initializing javax.security.auth.login.Configuration retains a static reference to the context 
                 * class loader.
                 */
            if (securityLoginConfigurationProtection) {
                try {
                    Class.forName("javax.security.auth.login.Configuration", true, ClassLoader.getSystemClassLoader());
                } catch (ClassNotFoundException e) {
                }
            }
            /*
                 * Creating a MessageDigest during web application startup
                 * initializes the Java Cryptography Architecture. Under certain
                 * conditions this starts a Token poller thread with TCCL equal
                 * to the web application class loader.
                 * 
                 * Instead we initialize JCA right now.
                 */
            if (tokenPollerProtection) {
                java.security.Security.getProviders();
            }
            // Set the default URL caching policy to not to cache
            if (urlCacheProtection) {
                try {
                    // Doesn't matter that this JAR doesn't exist - just as
                    // long as the URL is well-formed
                    URL url = new URL("jar:file://dummy.jar!/");
                    URLConnection uConn = url.openConnection();
                    uConn.setDefaultUseCaches(false);
                } catch (MalformedURLException e) {
                    log.error(sm.getString("jreLeakListener.jarUrlConnCacheFail"), e);
                } catch (IOException e) {
                    log.error(sm.getString("jreLeakListener.jarUrlConnCacheFail"), e);
                }
            }
            if (xmlParsingProtection) {
                // There are three known issues with XML parsing
                // 1. DocumentBuilderFactory.newInstance().newDocumentBuilder();
                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6916498
                // This issue is fixed in Java 7 onwards
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                try {
                    DocumentBuilder documentBuilder = factory.newDocumentBuilder();
                    // The 2nd and 3rd links both relate to cached Exception
                    // instances that retain a link to the TCCL via the
                    // backtrace field. Note that YourKit only shows this
                    // field when using the HPROF format memory snapshots.
                    // https://bz.apache.org/bugzilla/show_bug.cgi?id=58486
                    // These issues are currently present in all current
                    // versions of Java
                    // 2. com.sun.org.apache.xml.internal.serialize.DOMSerializerImpl
                    Document document = documentBuilder.newDocument();
                    document.createElement("dummy");
                    DOMImplementationLS implementation = (DOMImplementationLS) document.getImplementation();
                    implementation.createLSSerializer().writeToString(document);
                    // 3. com.sun.org.apache.xerces.internal.dom.DOMNormalizer
                    document.normalize();
                } catch (ParserConfigurationException e) {
                    log.error(sm.getString("jreLeakListener.xmlParseFail"), e);
                }
            }
            if (ldapPoolProtection) {
                try {
                    Class.forName("com.sun.jndi.ldap.LdapPoolManager");
                } catch (ClassNotFoundException e) {
                    if (System.getProperty("java.vendor").startsWith("Sun")) {
                        log.error(sm.getString("jreLeakListener.ldapPoolManagerFail"), e);
                    } else {
                        log.debug(sm.getString("jreLeakListener.ldapPoolManagerFail"), e);
                    }
                }
            }
            if (classesToInitialize != null) {
                StringTokenizer strTok = new StringTokenizer(classesToInitialize, ", \r\n\t");
                while (strTok.hasMoreTokens()) {
                    String classNameToLoad = strTok.nextToken();
                    try {
                        Class.forName(classNameToLoad);
                    } catch (ClassNotFoundException e) {
                        log.error(sm.getString("jreLeakListener.classToInitializeFail", classNameToLoad), e);
                    }
                }
            }
        } finally {
            Thread.currentThread().setContextClassLoader(loader);
        }
    }
}
Example 79
Project: tomcat70-master  File: JreMemoryLeakPreventionListener.java View source code
@Override
public void lifecycleEvent(LifecycleEvent event) {
    // Initialise these classes when Tomcat starts
    if (Lifecycle.BEFORE_INIT_EVENT.equals(event.getType())) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try {
            // Use the system classloader as the victim for all this
            // ClassLoader pinning we're about to do.
            Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
            /*
                 * First call to this loads all drivers in the current class
                 * loader
                 */
            if (driverManagerProtection) {
                DriverManager.getDrivers();
            }
            // be an issue.
            if (appContextProtection) {
                ImageIO.getCacheDirectory();
            }
            // etc.) thread
            if (awtThreadProtection) {
                java.awt.Toolkit.getDefaultToolkit();
            }
            // See https://bz.apache.org/bugzilla/show_bug.cgi?id=51687
            if (java2dDisposerProtection) {
                try {
                    Class.forName("sun.java2d.Disposer");
                } catch (ClassNotFoundException cnfe) {
                }
            }
            /*
                 * Several components end up calling
                 * sun.misc.GC.requestLatency(long) which creates a daemon
                 * thread without setting the TCCL.
                 *
                 * Those libraries / components known to trigger memory leaks
                 * due to eventual calls to requestLatency(long) are:
                 * - javax.management.remote.rmi.RMIConnectorServer.start()
                 *
                 * Note: Long.MAX_VALUE is a special case that causes the thread
                 *       to terminate
                 *
                 */
            if (gcDaemonProtection) {
                try {
                    Class<?> clazz = Class.forName("sun.misc.GC");
                    Method method = clazz.getDeclaredMethod("requestLatency", new Class[] { long.class });
                    method.invoke(null, Long.valueOf(Long.MAX_VALUE - 1));
                } catch (ClassNotFoundException e) {
                    if (JreVendor.IS_ORACLE_JVM) {
                        log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
                    } else {
                        log.debug(sm.getString("jreLeakListener.gcDaemonFail"), e);
                    }
                } catch (SecurityException e) {
                    log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
                } catch (NoSuchMethodException e) {
                    log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
                } catch (IllegalArgumentException e) {
                    log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
                } catch (IllegalAccessException e) {
                    log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
                } catch (InvocationTargetException e) {
                    ExceptionUtils.handleThrowable(e.getCause());
                    log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
                }
            }
            /*
                 * Calling getPolicy retains a static reference to the context
                 * class loader.
                 */
            if (securityPolicyProtection) {
                try {
                    // Policy.getPolicy();
                    Class<?> policyClass = Class.forName("javax.security.auth.Policy");
                    Method method = policyClass.getMethod("getPolicy");
                    method.invoke(null);
                } catch (ClassNotFoundException e) {
                } catch (SecurityException e) {
                } catch (NoSuchMethodException e) {
                    log.warn(sm.getString("jreLeakListener.authPolicyFail"), e);
                } catch (IllegalArgumentException e) {
                    log.warn(sm.getString("jreLeakListener.authPolicyFail"), e);
                } catch (IllegalAccessException e) {
                    log.warn(sm.getString("jreLeakListener.authPolicyFail"), e);
                } catch (InvocationTargetException e) {
                    ExceptionUtils.handleThrowable(e.getCause());
                    log.warn(sm.getString("jreLeakListener.authPolicyFail"), e);
                }
            }
            /*
                 * Initializing javax.security.auth.login.Configuration retains a static reference to the context
                 * class loader.
                 */
            if (securityLoginConfigurationProtection) {
                try {
                    Class.forName("javax.security.auth.login.Configuration", true, ClassLoader.getSystemClassLoader());
                } catch (ClassNotFoundException e) {
                }
            }
            /*
                 * Creating a MessageDigest during web application startup
                 * initializes the Java Cryptography Architecture. Under certain
                 * conditions this starts a Token poller thread with TCCL equal
                 * to the web application class loader.
                 *
                 * Instead we initialize JCA right now.
                 */
            if (tokenPollerProtection) {
                java.security.Security.getProviders();
            }
            // Set the default URL caching policy to not to cache
            if (urlCacheProtection) {
                try {
                    // Doesn't matter that this JAR doesn't exist - just as
                    // long as the URL is well-formed
                    URL url = new URL("jar:file://dummy.jar!/");
                    URLConnection uConn = url.openConnection();
                    uConn.setDefaultUseCaches(false);
                } catch (MalformedURLException e) {
                    log.error(sm.getString("jreLeakListener.jarUrlConnCacheFail"), e);
                } catch (IOException e) {
                    log.error(sm.getString("jreLeakListener.jarUrlConnCacheFail"), e);
                }
            }
            /*
                 * Various leaks related to the use of XML parsing.
                 */
            if (xmlParsingProtection) {
                // There are three known issues with XML parsing
                // 1. DocumentBuilderFactory.newInstance().newDocumentBuilder();
                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6916498
                // This issue is fixed in Java 7 onwards
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                try {
                    DocumentBuilder documentBuilder = factory.newDocumentBuilder();
                    // The 2nd and 3rd links both relate to cached Exception
                    // instances that retain a link to the TCCL via the
                    // backtrace field. Note that YourKit only shows this
                    // field when using the HPROF format memory snapshots.
                    // https://bz.apache.org/bugzilla/show_bug.cgi?id=58486
                    // These issues are currently present in all current
                    // versions of Java
                    // 2. com.sun.org.apache.xml.internal.serialize.DOMSerializerImpl
                    Document document = documentBuilder.newDocument();
                    document.createElement("dummy");
                    DOMImplementationLS implementation = (DOMImplementationLS) document.getImplementation();
                    implementation.createLSSerializer().writeToString(document);
                    // 3. com.sun.org.apache.xerces.internal.dom.DOMNormalizer
                    document.normalize();
                } catch (ParserConfigurationException e) {
                    log.error(sm.getString("jreLeakListener.xmlParseFail"), e);
                }
            }
            if (ldapPoolProtection) {
                try {
                    Class.forName("com.sun.jndi.ldap.LdapPoolManager");
                } catch (ClassNotFoundException e) {
                    if (JreVendor.IS_ORACLE_JVM) {
                        log.error(sm.getString("jreLeakListener.ldapPoolManagerFail"), e);
                    } else {
                        log.debug(sm.getString("jreLeakListener.ldapPoolManagerFail"), e);
                    }
                }
            }
            /*
                 * Present in Java 8 onwards
                 */
            if (forkJoinCommonPoolProtection && IS_JAVA_8_OR_LATER) {
                // Don't override any explicitly set property
                if (System.getProperty(FORK_JOIN_POOL_THREAD_FACTORY_PROPERTY) == null) {
                    System.setProperty(FORK_JOIN_POOL_THREAD_FACTORY_PROPERTY, "org.apache.catalina.startup.SafeForkJoinWorkerThreadFactory");
                }
            }
            if (classesToInitialize != null) {
                StringTokenizer strTok = new StringTokenizer(classesToInitialize, ", \r\n\t");
                while (strTok.hasMoreTokens()) {
                    String classNameToLoad = strTok.nextToken();
                    try {
                        Class.forName(classNameToLoad);
                    } catch (ClassNotFoundException e) {
                        log.error(sm.getString("jreLeakListener.classToInitializeFail", classNameToLoad), e);
                    }
                }
            }
        } finally {
            Thread.currentThread().setContextClassLoader(loader);
        }
    }
}
Example 80
Project: cdh3u3-with-mesos-master  File: UserGroupInformation.java View source code
/**
   * Set the configuration values for UGI.
   * @param conf the configuration to use
   */
private static synchronized void initialize(Configuration conf, boolean skipRulesSetting) {
    String value = conf.get(HADOOP_SECURITY_AUTHENTICATION);
    if (value == null || "simple".equals(value)) {
        useKerberos = false;
    } else if ("kerberos".equals(value)) {
        useKerberos = true;
    } else {
        throw new IllegalArgumentException("Invalid attribute value for " + HADOOP_SECURITY_AUTHENTICATION + " of " + value);
    }
    // If we haven't set up testing groups, use the configuration to find it
    if (!(groups instanceof TestingGroups)) {
        groups = Groups.getUserToGroupsMappingService(conf);
    }
    // Set the configuration for JAAS to be the Hadoop configuration. 
    // This is done here rather than a static initializer to avoid a
    // circular dependence.
    javax.security.auth.login.Configuration existingConfig = null;
    try {
        existingConfig = javax.security.auth.login.Configuration.getConfiguration();
    } catch (SecurityException se) {
    }
    if (existingConfig instanceof HadoopConfiguration) {
        LOG.info("JAAS Configuration already set up for Hadoop, not re-installing.");
    } else {
        javax.security.auth.login.Configuration.setConfiguration(new HadoopConfiguration(existingConfig));
    }
    // We're done initializing at this point. Important not to classload
    // KerberosName before this point, or else its static initializer
    // may call back into this same method!
    isInitialized = true;
    UserGroupInformation.conf = conf;
    // give the configuration on how to translate Kerberos names
    try {
        if (!skipRulesSetting) {
            KerberosName.setConfiguration(conf);
        }
    } catch (IOException ioe) {
        throw new RuntimeException("Problem with Kerberos auth_to_local name " + "configuration", ioe);
    }
}
Example 81
Project: hdfs-cloudera-cdh3u3-production-master  File: UserGroupInformation.java View source code
/**
   * Set the configuration values for UGI.
   * @param conf the configuration to use
   */
private static synchronized void initialize(Configuration conf, boolean skipRulesSetting) {
    String value = conf.get(HADOOP_SECURITY_AUTHENTICATION);
    if (value == null || "simple".equals(value)) {
        useKerberos = false;
    } else if ("kerberos".equals(value)) {
        useKerberos = true;
    } else {
        throw new IllegalArgumentException("Invalid attribute value for " + HADOOP_SECURITY_AUTHENTICATION + " of " + value);
    }
    // If we haven't set up testing groups, use the configuration to find it
    if (!(groups instanceof TestingGroups)) {
        groups = Groups.getUserToGroupsMappingService(conf);
    }
    // Set the configuration for JAAS to be the Hadoop configuration. 
    // This is done here rather than a static initializer to avoid a
    // circular dependence.
    javax.security.auth.login.Configuration existingConfig = null;
    try {
        existingConfig = javax.security.auth.login.Configuration.getConfiguration();
    } catch (SecurityException se) {
    }
    if (existingConfig instanceof HadoopConfiguration) {
        LOG.info("JAAS Configuration already set up for Hadoop, not re-installing.");
    } else {
        javax.security.auth.login.Configuration.setConfiguration(new HadoopConfiguration(existingConfig));
    }
    // We're done initializing at this point. Important not to classload
    // KerberosName before this point, or else its static initializer
    // may call back into this same method!
    isInitialized = true;
    UserGroupInformation.conf = conf;
    // give the configuration on how to translate Kerberos names
    try {
        if (!skipRulesSetting) {
            KerberosName.setConfiguration(conf);
        }
    } catch (IOException ioe) {
        throw new RuntimeException("Problem with Kerberos auth_to_local name " + "configuration", ioe);
    }
}
Example 82
Project: nifi-master  File: SolrProcessor.java View source code
@Override
protected final Collection<ValidationResult> customValidate(ValidationContext context) {
    final List<ValidationResult> problems = new ArrayList<>();
    if (SOLR_TYPE_CLOUD.equals(context.getProperty(SOLR_TYPE).getValue())) {
        final String collection = context.getProperty(COLLECTION).getValue();
        if (collection == null || collection.trim().isEmpty()) {
            problems.add(new ValidationResult.Builder().subject(COLLECTION.getName()).input(collection).valid(false).explanation("A collection must specified for Solr Type of Cloud").build());
        }
    }
    // If a JAAS Client App Name is provided then the system property for the JAAS config file must be set,
    // and that config file must contain an entry for the name provided by the processor
    final String jaasAppName = context.getProperty(JAAS_CLIENT_APP_NAME).getValue();
    if (!StringUtils.isEmpty(jaasAppName)) {
        final String loginConf = System.getProperty(Krb5HttpClientConfigurer.LOGIN_CONFIG_PROP);
        if (StringUtils.isEmpty(loginConf)) {
            problems.add(new ValidationResult.Builder().subject(JAAS_CLIENT_APP_NAME.getDisplayName()).valid(false).explanation("the system property " + Krb5HttpClientConfigurer.LOGIN_CONFIG_PROP + " must be set when providing a JAAS Client App Name").build());
        } else {
            final Configuration config = javax.security.auth.login.Configuration.getConfiguration();
            if (config.getAppConfigurationEntry(jaasAppName) == null) {
                problems.add(new ValidationResult.Builder().subject(JAAS_CLIENT_APP_NAME.getDisplayName()).valid(false).explanation("'" + jaasAppName + "' does not exist in " + loginConf).build());
            }
        }
    }
    // we can validate if the url starts with https we need an SSLContextService, if it starts with http we can't have an SSLContextService
    if (SOLR_TYPE_STANDARD.equals(context.getProperty(SOLR_TYPE).getValue())) {
        final String solrLocation = context.getProperty(SOLR_LOCATION).evaluateAttributeExpressions().getValue();
        if (solrLocation != null) {
            final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
            if (solrLocation.startsWith("https:") && sslContextService == null) {
                problems.add(new ValidationResult.Builder().subject(SSL_CONTEXT_SERVICE.getDisplayName()).valid(false).explanation("an SSLContextService must be provided when using https").build());
            } else if (solrLocation.startsWith("http:") && sslContextService != null) {
                problems.add(new ValidationResult.Builder().subject(SSL_CONTEXT_SERVICE.getDisplayName()).valid(false).explanation("an SSLContextService can not be provided when using http").build());
            }
        }
    }
    // Validate that we username and password are provided together, or that neither are provided
    final String username = context.getProperty(BASIC_USERNAME).evaluateAttributeExpressions().getValue();
    final String password = context.getProperty(BASIC_PASSWORD).evaluateAttributeExpressions().getValue();
    if (!StringUtils.isBlank(username) && StringUtils.isBlank(password)) {
        problems.add(new ValidationResult.Builder().subject(BASIC_PASSWORD.getDisplayName()).valid(false).explanation("a password must be provided for the given username").build());
    }
    if (!StringUtils.isBlank(password) && StringUtils.isBlank(username)) {
        problems.add(new ValidationResult.Builder().subject(BASIC_USERNAME.getDisplayName()).valid(false).explanation("a username must be provided for the given password").build());
    }
    Collection<ValidationResult> otherProblems = this.additionalCustomValidation(context);
    if (otherProblems != null) {
        problems.addAll(otherProblems);
    }
    return problems;
}
Example 83
Project: spring-hadoop-master  File: ExecutionUtils.java View source code
static ClassLoader createParentLastClassLoader(Resource jar, ClassLoader parentClassLoader, Configuration cfg) {
    ClassLoader cl = null;
    // sanity check
    if (parentClassLoader == null) {
        parentClassLoader = ClassUtils.getDefaultClassLoader();
        cl = parentClassLoader;
    }
    // check if a custom CL is needed
    if (jar != null) {
        // check if unjarring is required (it's a legacy JAR)
        try {
            if (isLegacyJar(jar)) {
                URL[] extractedURLs = expandedJarClassPath(jar, cfg);
                cl = new ParentLastURLClassLoader(extractedURLs, parentClassLoader);
            } else {
                cl = new ParentLastURLClassLoader(new URL[] { jar.getURL() }, parentClassLoader);
            }
        } catch (IOException e) {
            throw new IllegalStateException("Cannot open jar file", e);
        }
    }
    return cl;
}
Example 84
Project: yarn-comment-master  File: TestUserGroupInformation.java View source code
/** configure ugi */
@BeforeClass
public static void setup() {
    Configuration conf = new Configuration();
    conf.set("hadoop.security.auth_to_local", "RULE:[2:$1@$0](.*@HADOOP.APACHE.ORG)s/@.*//" + "RULE:[1:$1@$0](.*@HADOOP.APACHE.ORG)s/@.*//" + "DEFAULT");
    UserGroupInformation.setConfiguration(conf);
    javax.security.auth.login.Configuration.setConfiguration(new DummyLoginConfiguration());
}
Example 85
Project: airlift-master  File: SpnegoAuthentication.java View source code
private synchronized Session getSession() throws LoginException, GSSException {
    if (clientSession == null || clientSession.getClientCredential().getRemainingLifetime() < MIN_CREDENTIAL_LIFE_TIME.getValue(TimeUnit.SECONDS)) {
        // TODO: do we need to call logout() on the LoginContext?
        LoginContext loginContext = new LoginContext("", null, null, new Configuration() {

            @Override
            public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
                ImmutableMap.Builder<String, String> optionsBuilder = ImmutableMap.builder();
                optionsBuilder.put("refreshKrb5Config", "true");
                optionsBuilder.put("doNotPrompt", "true");
                optionsBuilder.put("useKeyTab", "true");
                if (LOG.isDebugEnabled()) {
                    optionsBuilder.put("debug", "true");
                }
                if (keytab != null) {
                    optionsBuilder.put("keyTab", keytab.getAbsolutePath());
                }
                if (credentialCache != null) {
                    optionsBuilder.put("ticketCache", credentialCache.getAbsolutePath());
                    optionsBuilder.put("useTicketCache", "true");
                    optionsBuilder.put("renewTGT", "true");
                }
                if (principal != null) {
                    optionsBuilder.put("principal", principal);
                }
                return new AppConfigurationEntry[] { new AppConfigurationEntry(Krb5LoginModule.class.getName(), REQUIRED, optionsBuilder.build()) };
            }
        });
        loginContext.login();
        Subject subject = loginContext.getSubject();
        Principal clientPrincipal = subject.getPrincipals().iterator().next();
        GSSCredential clientCredential = doAs(subject, () -> GSS_MANAGER.createCredential(GSS_MANAGER.createName(clientPrincipal.getName(), NT_USER_NAME), DEFAULT_LIFETIME, KERBEROS_OID, INITIATE_ONLY));
        clientSession = new Session(loginContext, clientCredential);
    }
    return clientSession;
}
Example 86
Project: elasticsearch-master  File: Loggers.java View source code
public static void setLevel(Logger logger, Level level) {
    if (!LogManager.ROOT_LOGGER_NAME.equals(logger.getName())) {
        Configurator.setLevel(logger.getName(), level);
    } else {
        final LoggerContext ctx = LoggerContext.getContext(false);
        final Configuration config = ctx.getConfiguration();
        final LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName());
        loggerConfig.setLevel(level);
        ctx.updateLoggers();
    }
    // we have to descend the hierarchy
    final LoggerContext ctx = LoggerContext.getContext(false);
    for (final LoggerConfig loggerConfig : ctx.getConfiguration().getLoggers().values()) {
        if (LogManager.ROOT_LOGGER_NAME.equals(logger.getName()) || loggerConfig.getName().startsWith(logger.getName() + ".")) {
            Configurator.setLevel(loggerConfig.getName(), level);
        }
    }
}
Example 87
Project: eucalyptus-master  File: GssapiKrb5Authenticator.java View source code
/**
   * See {@link com.eucalyptus.auth.euare.ldap.authentication.LdapAuthenticator}
   * <p>
   *  extraArgs[0] is the path of krb5.conf
   * </p>
   */
@Override
public LdapContext authenticate(final String serverUrl, String method, final boolean useSsl, final boolean ignoreSslCert, final String login, final String password, Object... extraArgs) throws LdapException {
    if (Strings.isNullOrEmpty(login) || Strings.isNullOrEmpty(password)) {
        throw new LdapException("LDAP login failed: empty login name or password");
    }
    if (extraArgs.length < 1 || !(extraArgs[0] instanceof String) || Strings.isNullOrEmpty((String) extraArgs[0])) {
        throw new LdapException("GSSAPI w/ Kerberos V5 requires krb5.conf argument");
    }
    System.setProperty(KRB5_CONF_PROPERTY, (String) extraArgs[0]);
    final Map<String, String> options = new HashMap<String, String>();
    options.put(JAAS_CONF_OPTION_CLIENT, "TRUE");
    final Configuration configuration = new Configuration() {

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return new AppConfigurationEntry[] { new AppConfigurationEntry(KRB5_LOGIN_MODULE, AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options) };
        }
    };
    final CallbackHandler callbackHandler = new CallbackHandler() {

        @Override
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (int i = 0; i < callbacks.length; i++) {
                if (callbacks[i] instanceof NameCallback) {
                    NameCallback cb = (NameCallback) callbacks[i];
                    cb.setName(login);
                } else if (callbacks[i] instanceof PasswordCallback) {
                    PasswordCallback cb = (PasswordCallback) callbacks[i];
                    char[] pwBytes = new char[password.length()];
                    password.getChars(0, pwBytes.length, pwBytes, 0);
                    cb.setPassword(pwBytes);
                }
            }
        }
    };
    // 1. Log in (to Kerberos)
    LoginContext loginContext = null;
    try {
        loginContext = new LoginContext(KRB5_LOGIN_CONTEXT_NAME, null, callbackHandler, configuration);
        loginContext.login();
    } catch (LoginException e) {
        LOG.error(e, e);
        throw new LdapException("Failed to login to Kerberos", e);
    }
    // 2. Perform JNDI work as logged in subject
    LdapContext ldapContext = Subject.<LdapContext>doAs(loginContext.getSubject(), new PrivilegedAction<LdapContext>() {

        @Override
        public LdapContext run() {
            Properties env = new Properties();
            env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CONTEXT_FACTORY);
            env.put(Context.REFERRAL, "follow");
            env.put(Context.PROVIDER_URL, serverUrl);
            env.put(Context.SECURITY_AUTHENTICATION, LicParser.LDAP_AUTH_METHOD_SASL_GSSAPI);
            if (useSsl) {
                env.put(Context.SECURITY_PROTOCOL, SSL_PROTOCOL);
                if (ignoreSslCert) {
                    env.put(SOCKET_FACTORY, EasySSLSocketFactory.class.getCanonicalName());
                }
            }
            try {
                return new InitialLdapContext(env, null);
            } catch (NamingException e) {
                LOG.error(e, e);
            }
            return null;
        }
    });
    if (ldapContext == null) {
        throw new LdapException("LDAP login failed, possibly wrong credential");
    }
    return ldapContext;
}
Example 88
Project: jboss-as-quickstart-master  File: RemoteClient.java View source code
public static LoginContext getCLMLoginContext(final String username, final String password) throws LoginException {
    final String configurationName = "Testing";
    CallbackHandler cbh = new CallbackHandler() {

        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback current : callbacks) {
                if (current instanceof NameCallback) {
                    ((NameCallback) current).setName(username);
                } else if (current instanceof PasswordCallback) {
                    ((PasswordCallback) current).setPassword(password.toCharArray());
                } else {
                    throw new UnsupportedCallbackException(current);
                }
            }
        }
    };
    Configuration config = new Configuration() {

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            if (configurationName.equals(name) == false) {
                throw new IllegalArgumentException("Unexpected configuration name '" + name + "'");
            }
            Map<String, String> options = new HashMap<String, String>();
            options.put("multi-threaded", "true");
            options.put("restore-login-identity", "true");
            AppConfigurationEntry clmEntry = new AppConfigurationEntry(ClientLoginModule.class.getName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
            return new AppConfigurationEntry[] { clmEntry };
        }
    };
    return new LoginContext(configurationName, new Subject(), cbh, config);
}
Example 89
Project: jst-master  File: ThriftClient.java View source code
public synchronized void reconnect() {
    close();
    try {
        TSocket socket = new TSocket(host, port);
        if (timeout != null) {
            socket.setTimeout(timeout);
        } else {
        // @@@ Todo
        // set the socket default Timeout as xxxx
        }
        // locate login configuration
        Configuration login_conf = AuthUtils.GetConfiguration(conf);
        // construct a transport plugin
        ITransportPlugin transportPlugin = AuthUtils.GetTransportPlugin(type, conf, login_conf);
        final TTransport underlyingTransport = socket;
        // TODO get this from type instead of hardcoding to Nimbus.
        // establish client-server transport via plugin
        // do retries if the connect fails
        TBackoffConnect connectionRetry = new TBackoffConnect(Utils.getInt(conf.get(Config.STORM_NIMBUS_RETRY_TIMES)), Utils.getInt(conf.get(Config.STORM_NIMBUS_RETRY_INTERVAL)), Utils.getInt(conf.get(Config.STORM_NIMBUS_RETRY_INTERVAL_CEILING)));
        _transport = connectionRetry.doConnectWithRetry(transportPlugin, underlyingTransport, host, asUser);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    _protocol = null;
    if (_transport != null) {
        _protocol = new TBinaryProtocol(_transport);
    }
}
Example 90
Project: jstorm-master  File: ThriftClient.java View source code
public synchronized void reconnect() {
    close();
    try {
        TSocket socket = new TSocket(host, port);
        if (timeout != null) {
            socket.setTimeout(timeout);
        } else {
        // @@@ Todo
        // set the socket default Timeout as xxxx
        }
        // locate login configuration
        Configuration login_conf = AuthUtils.GetConfiguration(conf);
        // construct a transport plugin
        ITransportPlugin transportPlugin = AuthUtils.GetTransportPlugin(type, conf, login_conf);
        final TTransport underlyingTransport = socket;
        // TODO get this from type instead of hardcoding to Nimbus.
        // establish client-server transport via plugin
        // do retries if the connect fails
        TBackoffConnect connectionRetry = new TBackoffConnect(Utils.getInt(conf.get(Config.STORM_NIMBUS_RETRY_TIMES)), Utils.getInt(conf.get(Config.STORM_NIMBUS_RETRY_INTERVAL)), Utils.getInt(conf.get(Config.STORM_NIMBUS_RETRY_INTERVAL_CEILING)));
        _transport = connectionRetry.doConnectWithRetry(transportPlugin, underlyingTransport, host, asUser);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    _protocol = null;
    if (_transport != null) {
        _protocol = new TBinaryProtocol(_transport);
    }
}
Example 91
Project: keycloak-master  File: KerberosJdkProvider.java View source code
@Override
public Configuration createJaasConfigurationForServer(final String keytab, final String serverPrincipal, final boolean debug) {
    return new Configuration() {

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            Map<String, Object> options = new HashMap<>();
            options.put("storeKey", "true");
            options.put("doNotPrompt", "true");
            options.put("isInitiator", "false");
            options.put("useKeyTab", "true");
            options.put("keyTab", keytab);
            options.put("principal", serverPrincipal);
            options.put("debug", String.valueOf(debug));
            AppConfigurationEntry kerberosLMConfiguration = new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
            return new AppConfigurationEntry[] { kerberosLMConfiguration };
        }
    };
}
Example 92
Project: pbase-master  File: DemoClient.java View source code
static Subject getSubject() throws Exception {
    if (!secure)
        return new Subject();
    /*
     * To authenticate the DemoClient, kinit should be invoked ahead.
     * Here we try to get the Kerberos credential from the ticket cache.
     */
    LoginContext context = new LoginContext("", new Subject(), null, new Configuration() {

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            Map<String, String> options = new HashMap<String, String>();
            options.put("useKeyTab", "false");
            options.put("storeKey", "false");
            options.put("doNotPrompt", "true");
            options.put("useTicketCache", "true");
            options.put("renewTGT", "true");
            options.put("refreshKrb5Config", "true");
            options.put("isInitiator", "true");
            String ticketCache = System.getenv("KRB5CCNAME");
            if (ticketCache != null) {
                options.put("ticketCache", ticketCache);
            }
            options.put("debug", "true");
            return new AppConfigurationEntry[] { new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options) };
        }
    });
    context.login();
    return context.getSubject();
}
Example 93
Project: quickstart-master  File: RemoteClient.java View source code
public static LoginContext getCLMLoginContext(final String username, final String password) throws LoginException {
    final String configurationName = "Testing";
    CallbackHandler cbh = new CallbackHandler() {

        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback current : callbacks) {
                if (current instanceof NameCallback) {
                    ((NameCallback) current).setName(username);
                } else if (current instanceof PasswordCallback) {
                    ((PasswordCallback) current).setPassword(password.toCharArray());
                } else {
                    throw new UnsupportedCallbackException(current);
                }
            }
        }
    };
    Configuration config = new Configuration() {

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            if (configurationName.equals(name) == false) {
                throw new IllegalArgumentException("Unexpected configuration name '" + name + "'");
            }
            Map<String, String> options = new HashMap<>();
            options.put("multi-threaded", "true");
            options.put("restore-login-identity", "true");
            AppConfigurationEntry clmEntry = new AppConfigurationEntry(ClientLoginModule.class.getName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
            return new AppConfigurationEntry[] { clmEntry };
        }
    };
    return new LoginContext(configurationName, new Subject(), cbh, config);
}
Example 94
Project: rest-utils-master  File: SaslTest.java View source code
@Before
public void setUp() throws Exception {
    jaasFile = File.createTempFile("jaas", ".config");
    loginPropertiesFile = File.createTempFile("login", ".properties");
    String jaas = "c3 {\n" + "  org.eclipse.jetty.jaas.spi.PropertyFileLoginModule required\n" + "  debug=\"true\"\n" + "  file=\"" + loginPropertiesFile.getAbsolutePath() + "\";\n" + "};\n";
    Files.write(jaasFile.toPath(), jaas.getBytes(StandardCharsets.UTF_8), StandardOpenOption.TRUNCATE_EXISTING);
    String loginProperties = "jay: kafka,Administrators\n" + "neha: akfak,Administrators\n" + "jun: kafka-\n";
    Files.write(loginPropertiesFile.toPath(), loginProperties.getBytes(StandardCharsets.UTF_8), StandardOpenOption.TRUNCATE_EXISTING);
    previousAuthConfig = System.getProperty("java.security.auth.login.config");
    Configuration.setConfiguration(null);
    System.setProperty("java.security.auth.login.config", jaasFile.getAbsolutePath());
    httpclient = HttpClients.createDefault();
    TestMetricsReporter.reset();
    Properties props = new Properties();
    props.put(RestConfig.LISTENERS_CONFIG, httpUri);
    props.put(RestConfig.METRICS_REPORTER_CLASSES_CONFIG, "io.confluent.rest.TestMetricsReporter");
    configBasic(props);
    TestRestConfig config = new TestRestConfig(props);
    app = new SaslTestApplication(config);
    app.start();
}
Example 95
Project: sonar-plugins-master  File: Ldap.java View source code
/**
   * Checks password using GSSAPI.
   *
   * @param principal principal
   * @param password  password
   * @return true, if principal can be authenticated with specified password
   */
private boolean checkPasswordUsingGssapi(String principal, String password) {
    // Use our custom configuration to avoid reliance on external config
    Configuration.setConfiguration(new Krb5LoginConfiguration());
    LoginContext lc;
    try {
        lc = new LoginContext(getClass().getName(), new CallbackHandlerImpl(principal, password));
        lc.login();
    } catch (LoginException e) {
        LdapHelper.LOG.debug("Password is not valid for principal: " + principal, e);
        return false;
    }
    try {
        lc.logout();
    } catch (LoginException e) {
        LdapHelper.LOG.warn("Logout fails", e);
    }
    return true;
}
Example 96
Project: tinkerpop-master  File: JaasKrbUtil.java View source code
public static Subject loginUsingPassword(String principal, String password) throws LoginException {
    Set<Principal> principals = new HashSet<Principal>();
    principals.add(new KerberosPrincipal(principal));
    Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
    Configuration conf = usePassword(principal);
    String confName = "PasswordConf";
    CallbackHandler callback = new KrbCallbackHandler(principal, password);
    LoginContext loginContext = new LoginContext(confName, subject, callback, conf);
    loginContext.login();
    return loginContext.getSubject();
}
Example 97
Project: vco-powershel-plugin-master  File: KerberosTokenGenerator.java View source code
// Authenticate against the KDC using JAAS.
private void login(final NTUser userName, final String password) throws LoginException {
    this.subject = new Subject();
    LoginContext login;
    login = new LoginContext("", subject, new CallbackHandler() {

        @Override
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback callback : callbacks) {
                if (callback instanceof NameCallback) {
                    //We may need some more complete mapping between AD user domain and Kerberos realms  
                    String kerbUserSPN = userName.getUserName();
                    if (StringUtils.isNotBlank(userName.getDomain())) {
                        kerbUserSPN += "@" + userName.getDomain().toUpperCase();
                    }
                    log.debug("Kerberos login name: " + kerbUserSPN);
                    ((NameCallback) callback).setName(kerbUserSPN);
                } else if (callback instanceof PasswordCallback) {
                    ((PasswordCallback) callback).setPassword(password.toCharArray());
                }
            }
        }
    }, new Configuration() {

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            Map<String, String> config = new HashMap<String, String>();
            config.put("useTicketCache", "false");
            return new AppConfigurationEntry[] { new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, config) };
        }
    });
    login.login();
}
Example 98
Project: wildfly-elytron-master  File: JaasUtil.java View source code
static Subject login(final String userName, final char[] password, final boolean server, final String keyTabFile) throws LoginException {
    Subject theSubject = new Subject();
    CallbackHandler cbh = new UsernamePasswordCBH(userName, password);
    Configuration config;
    if (server) {
        config = createGssProxyConfiguration(userName, keyTabFile);
    } else {
        config = createJaasConfiguration(false);
    }
    LoginContext lc = new LoginContext("KDC", theSubject, cbh, config);
    lc.login();
    return theSubject;
}
Example 99
Project: wildfly-security-master  File: JaasUtil.java View source code
static Subject login(final String userName, final char[] password, final boolean server, final String keyTabFile) throws LoginException {
    Subject theSubject = new Subject();
    CallbackHandler cbh = new UsernamePasswordCBH(userName, password);
    Configuration config;
    if (server) {
        config = createGssProxyConfiguration(userName, keyTabFile);
    } else {
        config = createJaasConfiguration(false);
    }
    LoginContext lc = new LoginContext("KDC", theSubject, cbh, config);
    lc.login();
    return theSubject;
}
Example 100
Project: zkclient-master  File: SaslAuthenticatedTest.java View source code
private void bootstrap() throws IOException {
    Configuration.setConfiguration(null);
    String jaasFileName = createJaasFile();
    System.setProperty(ZK_AUTH_PROVIDER, "org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
    System.setProperty(ZkClient.JAVA_LOGIN_CONFIG_PARAM, jaasFileName);
    _zkServer = TestUtil.startZkServer(_temporaryFolder, _port);
    _client = _zkServer.getZkClient();
}
Example 101
Project: JamVM-PH-master  File: GnuConfiguration.java View source code
// Class methods
// --------------------------------------------------------------------------
// Instance methods
// --------------------------------------------------------------------------
// Configuration abstract methods implementation ----------------------------
/* (non-Javadoc)
   * @see javax.security.auth.login.Configuration#getAppConfigurationEntry(java.lang.String)
   */
public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
    if (appName == null)
        return null;
    appName = appName.trim();
    if (appName.length() == 0)
        return null;
    List loginModules = (List) loginModulesMap.get(appName);
    if (loginModules == null || loginModules.size() == 0)
        return null;
    if (gnu.java.security.Configuration.DEBUG)
        log.fine(appName + " -> " + loginModules.size() + " entry(ies)");
    return (AppConfigurationEntry[]) loginModules.toArray(new AppConfigurationEntry[0]);
}