Search in sources :

Example 6 with AppConfigurationEntry

use of javax.security.auth.login.AppConfigurationEntry in project flink by apache.

the class TestingSecurityContext method install.

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);
    }
}
Also used : JaasModule(org.apache.flink.runtime.security.modules.JaasModule) AppConfigurationEntry(javax.security.auth.login.AppConfigurationEntry) DynamicConfiguration(org.apache.flink.runtime.security.DynamicConfiguration) Map(java.util.Map)

Example 7 with AppConfigurationEntry

use of javax.security.auth.login.AppConfigurationEntry in project hadoop by apache.

the class TestSecureRegistry method testLowlevelZKSaslLogin.

/**
  * 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();
    }
}
Also used : AppConfigurationEntry(javax.security.auth.login.AppConfigurationEntry) SaslServerCallbackHandler(org.apache.zookeeper.server.auth.SaslServerCallbackHandler) Login(org.apache.zookeeper.Login) Test(org.junit.Test)

Example 8 with AppConfigurationEntry

use of javax.security.auth.login.AppConfigurationEntry in project hbase by apache.

the class DemoClient method getSubject.

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<>();
            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();
}
Also used : AppConfigurationEntry(javax.security.auth.login.AppConfigurationEntry) LoginContext(javax.security.auth.login.LoginContext) Configuration(javax.security.auth.login.Configuration) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) SortedMap(java.util.SortedMap) Subject(javax.security.auth.Subject)

Example 9 with AppConfigurationEntry

use of javax.security.auth.login.AppConfigurationEntry in project hbase by apache.

the class HttpDoAsClient method getSubject.

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<>();
            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();
}
Also used : AppConfigurationEntry(javax.security.auth.login.AppConfigurationEntry) LoginContext(javax.security.auth.login.LoginContext) Configuration(javax.security.auth.login.Configuration) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) SortedMap(java.util.SortedMap) Subject(javax.security.auth.Subject)

Example 10 with AppConfigurationEntry

use of javax.security.auth.login.AppConfigurationEntry in project kafka by apache.

the class KerberosLogin method login.

/**
     * Performs login for each login module specified for the login context of this instance and starts the thread used
     * to periodically re-login to the Kerberos Ticket Granting Server.
     */
@Override
public LoginContext login() throws LoginException {
    this.lastLogin = currentElapsedTime();
    loginContext = super.login();
    subject = loginContext.getSubject();
    isKrbTicket = !subject.getPrivateCredentials(KerberosTicket.class).isEmpty();
    List<AppConfigurationEntry> entries = jaasContext().configurationEntries();
    if (entries.isEmpty()) {
        isUsingTicketCache = false;
        principal = null;
    } else {
        // there will only be a single entry
        AppConfigurationEntry entry = entries.get(0);
        if (entry.getOptions().get("useTicketCache") != null) {
            String val = (String) entry.getOptions().get("useTicketCache");
            isUsingTicketCache = val.equals("true");
        } else
            isUsingTicketCache = false;
        if (entry.getOptions().get("principal") != null)
            principal = (String) entry.getOptions().get("principal");
        else
            principal = null;
    }
    if (!isKrbTicket) {
        log.debug("[Principal={}]: It is not a Kerberos ticket", principal);
        t = null;
        // if no TGT, do not bother with ticket management.
        return loginContext;
    }
    log.debug("[Principal={}]: It is a Kerberos ticket", principal);
    // Refresh the Ticket Granting Ticket (TGT) periodically. How often to refresh is determined by the
    // TGT's existing expiry date and the configured minTimeBeforeRelogin. For testing and development,
    // you can decrease the interval of expiration of tickets (for example, to 3 minutes) by running:
    //  "modprinc -maxlife 3mins <principal>" in kadmin.
    t = Utils.newThread(String.format("kafka-kerberos-refresh-thread-%s", principal), new Runnable() {

        public void run() {
            log.info("[Principal={}]: TGT refresh thread started.", principal);
            while (true) {
                // renewal thread's main loop. if it exits from here, thread will exit.
                KerberosTicket tgt = getTGT();
                long now = currentWallTime();
                long nextRefresh;
                Date nextRefreshDate;
                if (tgt == null) {
                    nextRefresh = now + minTimeBeforeRelogin;
                    nextRefreshDate = new Date(nextRefresh);
                    log.warn("[Principal={}]: No TGT found: will try again at {}", principal, nextRefreshDate);
                } else {
                    nextRefresh = getRefreshTime(tgt);
                    long expiry = tgt.getEndTime().getTime();
                    Date expiryDate = new Date(expiry);
                    if (isUsingTicketCache && tgt.getRenewTill() != null && tgt.getRenewTill().getTime() < expiry) {
                        log.warn("The TGT cannot be renewed beyond the next expiry date: {}." + "This process will not be able to authenticate new SASL connections after that " + "time (for example, it will not be able to authenticate a new connection with a Kafka " + "Broker).  Ask your system administrator to either increase the " + "'renew until' time by doing : 'modprinc -maxrenewlife {} ' within " + "kadmin, or instead, to generate a keytab for {}. Because the TGT's " + "expiry cannot be further extended by refreshing, exiting refresh thread now.", expiryDate, principal, principal);
                        return;
                    }
                    // would cause ticket expiration.
                    if ((nextRefresh > expiry) || (now + minTimeBeforeRelogin > expiry)) {
                        // expiry is before next scheduled refresh).
                        log.info("[Principal={}]: Refreshing now because expiry is before next scheduled refresh time.", principal);
                        nextRefresh = now;
                    } else {
                        if (nextRefresh < (now + minTimeBeforeRelogin)) {
                            // next scheduled refresh is sooner than (now + MIN_TIME_BEFORE_LOGIN).
                            Date until = new Date(nextRefresh);
                            Date newUntil = new Date(now + minTimeBeforeRelogin);
                            log.warn("[Principal={}]: TGT refresh thread time adjusted from {} to {} since the former is sooner " + "than the minimum refresh interval ({} seconds) from now.", principal, until, newUntil, minTimeBeforeRelogin / 1000);
                        }
                        nextRefresh = Math.max(nextRefresh, now + minTimeBeforeRelogin);
                    }
                    nextRefreshDate = new Date(nextRefresh);
                    if (nextRefresh > expiry) {
                        log.error("[Principal={}]: Next refresh: {} is later than expiry {}. This may indicate a clock skew problem." + "Check that this host and the KDC hosts' clocks are in sync. Exiting refresh thread.", principal, nextRefreshDate, expiryDate);
                        return;
                    }
                }
                if (now < nextRefresh) {
                    Date until = new Date(nextRefresh);
                    log.info("[Principal={}]: TGT refresh sleeping until: {}", principal, until);
                    try {
                        Thread.sleep(nextRefresh - now);
                    } catch (InterruptedException ie) {
                        log.warn("[Principal={}]: TGT renewal thread has been interrupted and will exit.", principal);
                        return;
                    }
                } else {
                    log.error("[Principal={}]: NextRefresh: {} is in the past: exiting refresh thread. Check" + " clock sync between this host and KDC - (KDC's clock is likely ahead of this host)." + " Manual intervention will be required for this client to successfully authenticate." + " Exiting refresh thread.", principal, nextRefreshDate);
                    return;
                }
                if (isUsingTicketCache) {
                    String kinitArgs = "-R";
                    int retry = 1;
                    while (retry >= 0) {
                        try {
                            log.debug("[Principal={}]: Running ticket cache refresh command: {} {}", principal, kinitCmd, kinitArgs);
                            Shell.execCommand(kinitCmd, kinitArgs);
                            break;
                        } catch (Exception e) {
                            if (retry > 0) {
                                --retry;
                                // sleep for 10 seconds
                                try {
                                    Thread.sleep(10 * 1000);
                                } catch (InterruptedException ie) {
                                    log.error("[Principal={}]: Interrupted while renewing TGT, exiting Login thread", principal);
                                    return;
                                }
                            } else {
                                log.warn("[Principal={}]: Could not renew TGT due to problem running shell command: '{} {}'; " + "exception was: %s. Exiting refresh thread.", principal, kinitCmd, kinitArgs, e, e);
                                return;
                            }
                        }
                    }
                }
                try {
                    int retry = 1;
                    while (retry >= 0) {
                        try {
                            reLogin();
                            break;
                        } catch (LoginException le) {
                            if (retry > 0) {
                                --retry;
                                // sleep for 10 seconds.
                                try {
                                    Thread.sleep(10 * 1000);
                                } catch (InterruptedException e) {
                                    log.error("[Principal={}]: Interrupted during login retry after LoginException:", principal, le);
                                    throw le;
                                }
                            } else {
                                log.error("[Principal={}]: Could not refresh TGT.", principal, le);
                            }
                        }
                    }
                } catch (LoginException le) {
                    log.error("[Principal={}]: Failed to refresh TGT: refresh thread exiting now.", principal, le);
                    return;
                }
            }
        }
    }, true);
    t.start();
    return loginContext;
}
Also used : AppConfigurationEntry(javax.security.auth.login.AppConfigurationEntry) KerberosTicket(javax.security.auth.kerberos.KerberosTicket) LoginException(javax.security.auth.login.LoginException) Date(java.util.Date) LoginException(javax.security.auth.login.LoginException)

Aggregations

AppConfigurationEntry (javax.security.auth.login.AppConfigurationEntry)74 HashMap (java.util.HashMap)30 Configuration (javax.security.auth.login.Configuration)25 Map (java.util.Map)13 Test (org.junit.Test)11 Subject (javax.security.auth.Subject)10 LoginContext (javax.security.auth.login.LoginContext)10 SSOException (com.iplanet.sso.SSOException)7 SMSException (com.sun.identity.sm.SMSException)7 HashSet (java.util.HashSet)7 JaasRealm (org.apache.karaf.jaas.config.JaasRealm)7 Set (java.util.Set)6 LoginException (javax.security.auth.login.LoginException)5 IOException (java.io.IOException)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 CallbackHandler (javax.security.auth.callback.CallbackHandler)4 LoginModuleControlFlag (javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag)4 LoginModuleImpl (org.apache.jackrabbit.oak.security.authentication.user.LoginModuleImpl)4 File (java.io.File)3 Principal (java.security.Principal)3