Пример #1
0
  private synchronized void serviceLogin() throws AuthLoginException {
    debug.message("New Service Login ...");
    System.setProperty("java.security.krb5.realm", kdcRealm);
    System.setProperty("java.security.krb5.kdc", kdcServer);
    System.setProperty("java.security.auth.login.config", "/dev/null");

    try {
      Configuration config = Configuration.getConfiguration();
      WindowsDesktopSSOConfig wtc = null;
      if (config instanceof WindowsDesktopSSOConfig) {
        wtc = (WindowsDesktopSSOConfig) config;
        wtc.setRefreshConfig("true");
      } else {
        wtc = new WindowsDesktopSSOConfig(config);
      }
      wtc.setPrincipalName(servicePrincipalName);
      wtc.setKeyTab(keyTabFile);
      Configuration.setConfiguration(wtc);

      // perform service authentication using JDK Kerberos module
      LoginContext lc = new LoginContext(WindowsDesktopSSOConfig.defaultAppName);
      lc.login();

      serviceSubject = lc.getSubject();
      debug.message("Service login succeeded.");
    } catch (Exception e) {
      debug.error("Service Login Error: ");
      if (debug.messageEnabled()) {
        debug.message("Stack trace: ", e);
      }
      throw new AuthLoginException(amAuthWindowsDesktopSSO, "serviceAuth", null, e);
    }
  }
  /**
   * Set the configuration values for UGI.
   *
   * @param conf the configuration to use
   */
  private static synchronized void initialize(Configuration conf) {
    String value = conf.get(HADOOP_SECURITY_AUTHENTICATION);
    if (value == null || "simple".equals(value)) {
      useKerberos = false;
      useConfiguredFileAuth = false;
    } else if ("kerberos".equals(value)) {
      useKerberos = true;
      useConfiguredFileAuth = false;
    } else if ("configfile".equals(value)) {
      useKerberos = false;
      useConfiguredFileAuth = true;
    } else {
      throw new IllegalArgumentException(
          "Invalid attribute value for " + HADOOP_SECURITY_AUTHENTICATION + " of " + value);
    }

    // The getUserToGroupsMappingService will change the conf value, record the UGI information
    // firstly
    if (configUGIInformation == null) {
      configUGIInformation = conf.getStrings("hadoop.client.ugi");
    }

    // 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 no security configuration is on the classpath, then
      // we catch this exception, and we don't need to delegate
      // to anyone
    }

    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 {
      KerberosName.setConfiguration(conf);
    } catch (IOException ioe) {
      throw new RuntimeException(
          "Problem with Kerberos auth_to_local name " + "configuration", ioe);
    }
  }
Пример #3
0
  @After
  public void tearDown() throws Exception {
    Configuration.setConfiguration(null);

    _jaasAuthTypeField.set(null, _jaasAuthType);
    _jaasEnabledField.set(null, _jaasEnabled);
  }
  /** {@inheritDoc} */
  @Override
  public void start(StartContext arg0) throws StartException {
    if (log.isDebugEnabled()) log.debug("Starting JaasConfigurationService");

    // set new configuration
    Configuration.setConfiguration(configuration);
  }
  private void setConfiguration(
      Set<String> userNames, Set<String> groupNames, boolean loginShouldSucceed) {
    HashMap<String, String> configOptions = new HashMap<String, String>();

    String userNamesString;
    {
      Iterator<String> iter = userNames.iterator();
      userNamesString = "" + (iter.hasNext() ? iter.next() : "");
      while (iter.hasNext()) {
        userNamesString += "," + iter.next();
      }
    }

    String groupNamesString = "";
    {
      Iterator<String> iter = groupNames.iterator();
      groupNamesString = "" + (iter.hasNext() ? iter.next() : "");
      while (iter.hasNext()) {
        groupNamesString += "," + iter.next();
      }
    }

    configOptions.put(StubLoginModule.ALLOW_LOGIN_PROPERTY, loginShouldSucceed ? "true" : "false");
    configOptions.put(StubLoginModule.USERS_PROPERTY, userNamesString);
    configOptions.put(StubLoginModule.GROUPS_PROPERTY, groupNamesString);
    AppConfigurationEntry configEntry =
        new AppConfigurationEntry(
            "org.apache.activemq.security.StubLoginModule",
            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
            configOptions);

    StubJaasConfiguration jaasConfig = new StubJaasConfiguration(configEntry);

    Configuration.setConfiguration(jaasConfig);
  }
Пример #6
0
  private static void validate(
      final String username,
      final String password,
      final String krbfile,
      final String loginfile,
      final String moduleName)
      throws FileNotFoundException, NoSuchAlgorithmException {

    // confirm username was provided
    if (null == username || username.isEmpty()) {
      throw new IllegalArgumentException("Must provide a username");
    }

    // confirm password was provided
    if (null == password || password.isEmpty()) {
      throw new IllegalArgumentException("Must provide a password");
    }

    // confirm krb5.conf file exists
    if (null == krbfile || krbfile.isEmpty()) {
      throw new IllegalArgumentException("Must provide a krb5 file");
    } else {
      final File file = new File(krbfile);
      if (!file.exists()) {
        throw new FileNotFoundException(krbfile);
      }
    }

    // confirm loginfile
    if (null == loginfile || loginfile.isEmpty()) {
      throw new IllegalArgumentException("Must provide a login file");
    } else {
      final File file = new File(loginfile);
      if (!file.exists()) {
        throw new FileNotFoundException(loginfile);
      }
    }

    // confirm that runtime loaded the login file
    final Configuration config = Configuration.getConfiguration();

    // confirm that the module name exists in the file
    if (null == config.getAppConfigurationEntry(moduleName)) {
      throw new IllegalArgumentException(
          "The module name " + moduleName + " was not found in the login file");
    }
  }
Пример #7
0
 static {
   try {
     Configuration.setConfiguration(new TestConfig());
     System.out.println("Installed TestConfig as JAAS Configuration");
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Пример #8
0
  /**
   * Setup a JAAS Configuration that handles a fake app. This runs before UserGroupInformation has
   * been initialized, so UGI picks up this Configuration as the parent.
   */
  private static void setupMockJaasParent() {
    javax.security.auth.login.Configuration existing = null;
    try {
      existing = javax.security.auth.login.Configuration.getConfiguration();
      assertFalse(
          "setupMockJaasParent should run before the Hadoop "
              + "configuration provider is installed.",
          existing.getClass().getCanonicalName().startsWith("org.apache.hadoop"));
    } catch (SecurityException se) {
      // We get this if no configuration has been set. So it's OK.
    }

    mockJaasConf = mock(javax.security.auth.login.Configuration.class);
    Mockito.doReturn(new AppConfigurationEntry[] {})
        .when(mockJaasConf)
        .getAppConfigurationEntry("foobar-app");
    javax.security.auth.login.Configuration.setConfiguration(mockJaasConf);
  }
Пример #9
0
  public static void main(String[] args) {

    Configuration config = null;
    try {
      config = Configuration.getConfiguration();
    } catch (SecurityException se) {
      System.out.println("test 1 failed");
      throw se;
    }

    AppConfigurationEntry[] entries = config.getAppConfigurationEntry("InnerClassConfig");

    System.out.println("module = " + entries[0].getLoginModuleName());
    if (entries[0].getLoginModuleName().equals("package.Foo$Bar")) {
      System.out.println("test succeeded");
    } else {
      System.out.println("test 2 failed");
      throw new SecurityException("package name incorrect");
    }
  }
  @SuppressWarnings("deprecation")
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    // load it up with example1.ldif
    String fileName = targetDir + "ldap" + fs + "example1.ldif";
    boolean op = util.addLDIF(serverHost, port, adminDN, adminPW, new File(fileName).toURL());
    assertTrue(op);

    // Setup a configuration
    Configuration.setConfiguration(
        new Configuration() {
          @SuppressWarnings("unchecked")
          @Override
          public AppConfigurationEntry[] getAppConfigurationEntry(String cname) {
            String name = LdapLoginModule.class.getName();
            HashMap options = new HashMap();

            options.put("java.naming.factory.initial", ldapCtxFactory);
            options.put("java.naming.provider.url", "ldap://localhost:10389/");
            options.put("java.naming.security.authentication", "simple");
            options.put("principalDNPrefix", "uid=");
            options.put("uidAttributeID", "userid");
            options.put("roleAttributeID", "roleName");
            options.put("principalDNSuffix", ",ou=People,dc=jboss,dc=org");
            options.put("rolesCtxDN", "cn=JBossSX Tests,ou=Roles,dc=jboss,dc=org");
            options.put(Context.SECURITY_CREDENTIALS, "somecrazyencryptedstring");
            options.put("jaasSecurityDomain", oname);

            AppConfigurationEntry ace =
                new AppConfigurationEntry(
                    name, AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
            AppConfigurationEntry[] entry = {ace};
            return entry;
          }

          @Override
          public void refresh() {}
        });

    // Setup MBeanServer
    MBeanServer jbossMBeanServer = MBeanServerFactory.createMBeanServer("jboss");
    MBeanServerLocator.setJBoss(jbossMBeanServer);
    try {
      Test test = new Test();
      jbossMBeanServer.registerMBean(test, new ObjectName(oname));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #11
0
  @Before
  public void setUp() throws Exception {
    _jaasAuthTypeField =
        ReflectionUtil.getDeclaredField(PropsValues.class, "PORTAL_JAAS_AUTH_TYPE");

    _jaasAuthType = (String) _jaasAuthTypeField.get(null);

    _jaasEnabledField = ReflectionUtil.getDeclaredField(PropsValues.class, "PORTAL_JAAS_ENABLE");

    _jaasEnabled = (Boolean) _jaasEnabledField.get(null);

    _jaasEnabledField.set(null, true);

    Configuration.setConfiguration(new JAASConfiguration());

    _user = TestPropsValues.getUser();
  }
 @Override
 public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
   if (SIMPLE_CONFIG_NAME.equals(appName)) {
     return SIMPLE_CONF;
   } else if (USER_KERBEROS_CONFIG_NAME.equals(appName)) {
     return USER_KERBEROS_CONF;
   } else if (KEYTAB_KERBEROS_CONFIG_NAME.equals(appName)) {
     KEYTAB_KERBEROS_OPTIONS.put("keyTab", keytabFile);
     KEYTAB_KERBEROS_OPTIONS.put("principal", keytabPrincipal);
     return KEYTAB_KERBEROS_CONF;
   } else if (FILE_CONFIG_NAME.equals(appName)) {
     return FILE_CONF;
   } else if (parent != null) {
     return parent.getAppConfigurationEntry(appName);
   }
   return null;
 }
  @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);
  }
Пример #14
0
  /** Create a KerberosSaslNettyClient for authentication with servers. */
  public KerberosSaslNettyClient(Map storm_conf, String jaas_section) {
    LOG.debug(
        "KerberosSaslNettyClient: Creating SASL {} client to authenticate to server ",
        SaslUtils.KERBEROS);

    LOG.info("Creating Kerberos Client.");

    Configuration login_conf;
    try {
      login_conf = AuthUtils.GetConfiguration(storm_conf);
    } catch (Throwable t) {
      LOG.error("Failed to get login_conf: ", t);
      throw t;
    }
    LOG.debug("KerberosSaslNettyClient: authmethod {}", SaslUtils.KERBEROS);

    SaslClientCallbackHandler ch = new SaslClientCallbackHandler();

    subject = null;
    try {
      LOG.debug("Setting Configuration to login_config: {}", login_conf);
      // specify a configuration object to be used
      Configuration.setConfiguration(login_conf);
      // now login
      LOG.debug("Trying to login.");
      Login login = new Login(jaas_section, ch);
      subject = login.getSubject();
      LOG.debug("Got Subject: {}", subject.toString());
    } catch (LoginException ex) {
      LOG.error("Client failed to login in principal:" + ex, ex);
      throw new RuntimeException(ex);
    }

    // check the credential of our principal
    if (subject.getPrivateCredentials(KerberosTicket.class).isEmpty()) {
      LOG.error("Failed to verify user principal.");
      throw new RuntimeException(
          "Fail to verify user principal with section \""
              + jaas_section
              + "\" in login configuration file "
              + login_conf);
    }

    String serviceName = null;
    try {
      serviceName = AuthUtils.get(login_conf, jaas_section, "serviceName");
    } catch (IOException e) {
      LOG.error("Failed to get service name.", e);
      throw new RuntimeException(e);
    }

    try {
      Principal principal = (Principal) subject.getPrincipals().toArray()[0];
      final String fPrincipalName = principal.getName();
      final String fHost = (String) storm_conf.get(Config.PACEMAKER_HOST);
      final String fServiceName = serviceName;
      final CallbackHandler fch = ch;
      LOG.debug("Kerberos Client with principal: {}, host: {}", fPrincipalName, fHost);
      saslClient =
          Subject.doAs(
              subject,
              new PrivilegedExceptionAction<SaslClient>() {
                public SaslClient run() {
                  try {
                    Map<String, String> props = new TreeMap<String, String>();
                    props.put(Sasl.QOP, "auth");
                    props.put(Sasl.SERVER_AUTH, "false");
                    return Sasl.createSaslClient(
                        new String[] {SaslUtils.KERBEROS},
                        fPrincipalName,
                        fServiceName,
                        fHost,
                        props,
                        fch);
                  } catch (Exception e) {
                    LOG.error("Subject failed to create sasl client.", e);
                    return null;
                  }
                }
              });
      LOG.info("Got Client: {}", saslClient);

    } catch (PrivilegedActionException e) {
      LOG.error("KerberosSaslNettyClient: Could not create Sasl Netty Client.");
      throw new RuntimeException(e);
    }
  }
 /** {@inheritDoc} */
 @Override
 public void stop(StopContext arg0) {
   // restore configuration to null
   Configuration.setConfiguration(null);
 }
 @After
 public void tearDown() {
   Configuration.setConfiguration(null);
 }
Пример #17
0
  /**
   * Returns response body for the given URL request as a String. It also checks if the returned
   * HTTP status code is the expected one. If the server returns {@link
   * HttpServletResponse#SC_UNAUTHORIZED} and an username is provided, then the given user is
   * authenticated against Kerberos and a new request is executed under the new subject.
   *
   * @param uri URI to which the request should be made
   * @param user Username
   * @param pass Password
   * @param expectedStatusCode expected status code returned from the requested server
   * @return HTTP response body
   * @throws IOException
   * @throws URISyntaxException
   * @throws PrivilegedActionException
   * @throws LoginException
   */
  public static String makeCallWithKerberosAuthn(
      final URI uri, final String user, final String pass, final int expectedStatusCode)
      throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    LOGGER.info("Requesting URI: " + uri);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
      httpClient
          .getAuthSchemes()
          .register(AuthPolicy.SPNEGO, new JBossNegotiateSchemeFactory(true));
      httpClient
          .getCredentialsProvider()
          .setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());

      final HttpGet httpGet = new HttpGet(uri);
      final HttpResponse response = httpClient.execute(httpGet);
      int statusCode = response.getStatusLine().getStatusCode();
      if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
        assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
      }
      final HttpEntity entity = response.getEntity();
      final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
      assertTrue(
          "WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
      final Set<String> authnHeaderValues = new HashSet<String>();
      for (final Header header : authnHeaders) {
        authnHeaderValues.add(header.getValue());
      }
      assertTrue(
          "WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));

      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
      }
      if (entity != null) EntityUtils.consume(entity);

      // Use our custom configuration to avoid reliance on external config
      Configuration.setConfiguration(new Krb5LoginConfiguration());
      // 1. Authenticate to Kerberos.
      final LoginContext lc =
          new LoginContext(Utils.class.getName(), new UsernamePasswordHandler(user, pass));
      lc.login();

      // 2. Perform the work as authenticated Subject.
      final String responseBody =
          Subject.doAs(
              lc.getSubject(),
              new PrivilegedExceptionAction<String>() {
                public String run() throws Exception {
                  final HttpResponse response = httpClient.execute(httpGet);
                  int statusCode = response.getStatusLine().getStatusCode();
                  assertEquals(
                      "Unexpected status code returned after the authentication.",
                      expectedStatusCode,
                      statusCode);
                  return EntityUtils.toString(response.getEntity());
                }
              });
      lc.logout();
      return responseBody;
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpClient.getConnectionManager().shutdown();
    }
  }
Пример #18
0
 public static void init() {
   config = new JAASConfiguration();
   Configuration.setConfiguration(config);
 }
Пример #19
0
  /**
   * Creates request against SPNEGO protected web-app with FORM fallback. It tries to login using
   * SPNEGO first - if it fails, FORM is used.
   *
   * @param contextUrl
   * @param page
   * @param user
   * @param pass
   * @param expectedStatusCode
   * @return
   * @throws IOException
   * @throws URISyntaxException
   * @throws PrivilegedActionException
   * @throws LoginException
   */
  public static String makeHttpCallWithFallback(
      final String contextUrl,
      final String page,
      final String user,
      final String pass,
      final int expectedStatusCode)
      throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    final String strippedContextUrl = StringUtils.stripEnd(contextUrl, "/");
    final String url = strippedContextUrl + page;
    LOGGER.info("Requesting URL: " + url);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setRedirectStrategy(REDIRECT_STRATEGY);
    String unauthorizedPageBody = null;
    try {
      httpClient
          .getAuthSchemes()
          .register(AuthPolicy.SPNEGO, new JBossNegotiateSchemeFactory(true));
      httpClient
          .getCredentialsProvider()
          .setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());

      final HttpGet httpGet = new HttpGet(url);
      final HttpResponse response = httpClient.execute(httpGet);
      int statusCode = response.getStatusLine().getStatusCode();
      if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
        assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
      }
      final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
      assertTrue(
          "WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
      final Set<String> authnHeaderValues = new HashSet<String>();
      for (final Header header : authnHeaders) {
        authnHeaderValues.add(header.getValue());
      }
      assertTrue(
          "WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));

      LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
      unauthorizedPageBody = EntityUtils.toString(response.getEntity());

      // Use our custom configuration to avoid reliance on external config
      Configuration.setConfiguration(new Krb5LoginConfiguration());
      // 1. Authenticate to Kerberos.
      final LoginContext lc =
          new LoginContext(Utils.class.getName(), new UsernamePasswordHandler(user, pass));
      lc.login();

      // 2. Perform the work as authenticated Subject.
      final String responseBody =
          Subject.doAs(
              lc.getSubject(),
              new PrivilegedExceptionAction<String>() {
                public String run() throws Exception {
                  final HttpResponse response = httpClient.execute(httpGet);
                  int statusCode = response.getStatusLine().getStatusCode();
                  assertEquals(
                      "Unexpected status code returned after the authentication.",
                      expectedStatusCode,
                      statusCode);
                  return EntityUtils.toString(response.getEntity());
                }
              });
      lc.logout();
      return responseBody;
    } catch (LoginException e) {
      assertNotNull(unauthorizedPageBody);
      assertTrue(unauthorizedPageBody.contains("j_security_check"));

      HttpPost httpPost = new HttpPost(strippedContextUrl + "/j_security_check");
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
      nameValuePairs.add(new BasicNameValuePair("j_username", user));
      nameValuePairs.add(new BasicNameValuePair("j_password", pass));
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      final HttpResponse response = httpClient.execute(httpPost);
      int statusCode = response.getStatusLine().getStatusCode();
      assertEquals(
          "Unexpected status code returned after the authentication.",
          expectedStatusCode,
          statusCode);
      return EntityUtils.toString(response.getEntity());
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpClient.getConnectionManager().shutdown();
    }
  }