Example usage for org.apache.hadoop.security UserGroupInformation getAuthenticationMethod

List of usage examples for org.apache.hadoop.security UserGroupInformation getAuthenticationMethod

Introduction

In this page you can find the example usage for org.apache.hadoop.security UserGroupInformation getAuthenticationMethod.

Prototype

public synchronized AuthenticationMethod getAuthenticationMethod() 

Source Link

Document

Get the authentication method from the subject

Usage

From source file:org.apache.flink.yarn.AbstractYarnClusterDescriptor.java

License:Apache License

@Override
public YarnClusterClient deploy() {
    try {/*from   w w w .jav  a 2s . c  o m*/
        if (UserGroupInformation.isSecurityEnabled()) {
            // note: UGI::hasKerberosCredentials inaccurately reports false
            // for logins based on a keytab (fixed in Hadoop 2.6.1, see HADOOP-10786),
            // so we check only in ticket cache scenario.
            boolean useTicketCache = flinkConfiguration
                    .getBoolean(SecurityOptions.KERBEROS_LOGIN_USETICKETCACHE);

            UserGroupInformation loginUser = UserGroupInformation.getCurrentUser();
            if (loginUser.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.KERBEROS
                    && useTicketCache && !loginUser.hasKerberosCredentials()) {
                LOG.error(
                        "Hadoop security with Kerberos is enabled but the login user does not have Kerberos credentials");
                throw new RuntimeException("Hadoop security with Kerberos is enabled but the login user "
                        + "does not have Kerberos credentials");
            }
        }
        return deployInternal();
    } catch (Exception e) {
        throw new RuntimeException("Couldn't deploy Yarn cluster", e);
    }
}

From source file:org.apache.flume.auth.KerberosAuthenticator.java

License:Apache License

private void printUGI(UserGroupInformation ugi) {
    if (ugi != null) {
        // dump login information
        AuthenticationMethod authMethod = ugi.getAuthenticationMethod();
        LOG.info("\n{} \nUser: {} \nAuth method: {} \nKeytab: {} \n",
                new Object[] { authMethod.equals(AuthenticationMethod.PROXY) ? "Proxy as: " : "Logged as: ",
                        ugi.getUserName(), authMethod, ugi.isFromKeytab() });
    }//from ww  w . j  a v  a2 s.co m
}

From source file:org.apache.hoya.tools.HoyaUtils.java

License:Apache License

/**
 * Turn on security. This is setup to only run once.
 * @param conf configuration to build up security
 * @return true if security was initialized in this call
 * @throws IOException IO/Net problems//from  w w  w .  j  a  v a2  s  . c  o m
 * @throws BadConfigException the configuration and system state are inconsistent
 */
public static boolean initProcessSecurity(Configuration conf) throws IOException, BadConfigException {

    if (processSecurityAlreadyInitialized.compareAndSet(true, true)) {
        //security is already inited
        return false;
    }

    log.info("JVM initialized into secure mode with kerberos realm {}", HoyaUtils.getKerberosRealm());
    //this gets UGI to reset its previous world view (i.e simple auth)
    //security
    log.debug("java.security.krb5.realm={}", System.getProperty("java.security.krb5.realm", ""));
    log.debug("java.security.krb5.kdc={}", System.getProperty("java.security.krb5.kdc", ""));
    SecurityUtil.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS, conf);
    UserGroupInformation.setConfiguration(conf);
    UserGroupInformation authUser = UserGroupInformation.getCurrentUser();
    log.debug("Authenticating as " + authUser.toString());
    log.debug("Login user is {}", UserGroupInformation.getLoginUser());
    if (!UserGroupInformation.isSecurityEnabled()) {
        throw new BadConfigException("Although secure mode is enabled,"
                + "the application has already set up its user as an insecure entity %s", authUser);
    }
    if (authUser.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.SIMPLE) {
        throw new BadConfigException("Auth User is not Kerberized %s"
                + " -security has already been set up with the wrong authentication method", authUser);

    }

    HoyaUtils.verifyPrincipalSet(conf, YarnConfiguration.RM_PRINCIPAL);
    HoyaUtils.verifyPrincipalSet(conf, DFSConfigKeys.DFS_NAMENODE_USER_NAME_KEY);
    return true;
}

From source file:org.apache.slider.common.tools.SliderUtils.java

License:Apache License

/**
 * Turn on security. This is setup to only run once.
 * @param conf configuration to build up security
 * @return true if security was initialized in this call
 * @throws IOException IO/Net problems/*from w  w  w . j av a  2  s  . co  m*/
 * @throws BadConfigException the configuration and system state are inconsistent
 */
public static boolean initProcessSecurity(Configuration conf) throws IOException, BadConfigException {

    if (processSecurityAlreadyInitialized.compareAndSet(true, true)) {
        //security is already inited
        return false;
    }

    log.info("JVM initialized into secure mode with kerberos realm {}", SliderUtils.getKerberosRealm());
    //this gets UGI to reset its previous world view (i.e simple auth)
    //security
    log.debug("java.security.krb5.realm={}", System.getProperty(JAVA_SECURITY_KRB5_REALM, ""));
    log.debug("java.security.krb5.kdc={}", System.getProperty(JAVA_SECURITY_KRB5_KDC, ""));
    log.debug("hadoop.security.authentication={}",
            conf.get(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION));
    log.debug("hadoop.security.authorization={}",
            conf.get(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION));
    /*    SecurityUtil.setAuthenticationMethod(
            UserGroupInformation.AuthenticationMethod.KERBEROS, conf);*/
    UserGroupInformation.setConfiguration(conf);
    UserGroupInformation authUser = UserGroupInformation.getCurrentUser();
    log.debug("Authenticating as " + authUser.toString());
    log.debug("Login user is {}", UserGroupInformation.getLoginUser());
    if (!UserGroupInformation.isSecurityEnabled()) {
        throw new BadConfigException("Although secure mode is enabled,"
                + "the application has already set up its user as an insecure entity %s", authUser);
    }
    if (authUser.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.SIMPLE) {
        throw new BadConfigException("Auth User is not Kerberized %s"
                + " -security has already been set up with the wrong authentication method. "
                + "This can occur if a file system has already been created prior to the loading of "
                + "the security configuration.", authUser);

    }

    SliderUtils.verifyPrincipalSet(conf, YarnConfiguration.RM_PRINCIPAL);
    SliderUtils.verifyPrincipalSet(conf, DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY);
    return true;
}

From source file:org.apache.solr.security.DelegationTokenKerberosFilter.java

License:Apache License

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    // HttpClient 4.4.x throws NPE if query string is null and parsed through URLEncodedUtils.
    // See HTTPCLIENT-1746 and HADOOP-12767
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String queryString = httpRequest.getQueryString();
    final String nonNullQueryString = queryString == null ? "" : queryString;
    HttpServletRequest requestNonNullQueryString = new HttpServletRequestWrapper(httpRequest) {
        @Override//from   w w  w.j  a va2 s.co  m
        public String getQueryString() {
            return nonNullQueryString;
        }
    };

    // include Impersonator User Name in case someone (e.g. logger) wants it
    FilterChain filterChainWrapper = new FilterChain() {
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
                throws IOException, ServletException {
            HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

            UserGroupInformation ugi = HttpUserGroupInformation.get();
            if (ugi != null
                    && ugi.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.PROXY) {
                UserGroupInformation realUserUgi = ugi.getRealUser();
                if (realUserUgi != null) {
                    httpRequest.setAttribute(KerberosPlugin.IMPERSONATOR_USER_NAME,
                            realUserUgi.getShortUserName());
                }
            }
            filterChain.doFilter(servletRequest, servletResponse);
        }
    };

    super.doFilter(requestNonNullQueryString, response, filterChainWrapper);
}

From source file:org.kaaproject.kaa.server.flume.sink.hdfs.KaaHdfsSink.java

License:Apache License

private boolean authenticate() {

    // logic for kerberos login
    boolean useSecurity = UserGroupInformation.isSecurityEnabled();

    LOG.info("Hadoop Security enabled: " + useSecurity);

    if (useSecurity) {

        // sanity checking
        if (kerbConfPrincipal.isEmpty()) {
            LOG.error("Hadoop running in secure mode, but Flume config doesn't "
                    + "specify a principal to use for Kerberos auth.");
            return false;
        }//  w w  w .j ava  2s.  co m
        if (kerbKeytab.isEmpty()) {
            LOG.error("Hadoop running in secure mode, but Flume config doesn't "
                    + "specify a keytab to use for Kerberos auth.");
            return false;
        } else {
            //If keytab is specified, user should want it take effect.
            //HDFSSink will halt when keytab file is non-exist or unreadable
            File kfile = new File(kerbKeytab);
            if (!(kfile.isFile() && kfile.canRead())) {
                throw new IllegalArgumentException(
                        "The keyTab file: " + kerbKeytab + " is nonexistent or can't read. "
                                + "Please specify a readable keytab file for Kerberos auth.");
            }
        }

        String principal;
        try {
            // resolves _HOST pattern using standard Hadoop search/replace
            // via DNS lookup when 2nd argument is empty
            principal = SecurityUtil.getServerPrincipal(kerbConfPrincipal, "");
        } catch (IOException ex) {
            LOG.error("Host lookup error resolving kerberos principal (" + kerbConfPrincipal
                    + "). Exception follows.", ex);
            return false;
        }

        Preconditions.checkNotNull(principal, "Principal must not be null");
        KerberosUser prevUser = staticLogin.get();
        KerberosUser newUser = new KerberosUser(principal, kerbKeytab);

        // be cruel and unusual when user tries to login as multiple principals
        // this isn't really valid with a reconfigure but this should be rare
        // enough to warrant a restart of the agent JVM
        // TODO: find a way to interrogate the entire current config state,
        // since we don't have to be unnecessarily protective if they switch all
        // HDFS sinks to use a different principal all at once.
        Preconditions.checkState(prevUser == null || prevUser.equals(newUser),
                "Cannot use multiple kerberos principals in the same agent. "
                        + " Must restart agent to use new principal or keytab. " + "Previous = %s, New = %s",
                prevUser, newUser);

        // attempt to use cached credential if the user is the same
        // this is polite and should avoid flooding the KDC with auth requests
        UserGroupInformation curUser = null;
        if (prevUser != null && prevUser.equals(newUser)) {
            try {
                curUser = UserGroupInformation.getLoginUser();
            } catch (IOException ex) {
                LOG.warn("User unexpectedly had no active login. Continuing with " + "authentication", ex);
            }
        }

        if (curUser == null || !curUser.getUserName().equals(principal)) {
            try {
                // static login
                kerberosLogin(this, principal, kerbKeytab);
            } catch (IOException ex) {
                LOG.error("Authentication or file read error while attempting to "
                        + "login as kerberos principal (" + principal + ") using " + "keytab (" + kerbKeytab
                        + "). Exception follows.", ex);
                return false;
            }
        } else {
            LOG.debug("{}: Using existing principal login: {}", this, curUser);
        }

        // we supposedly got through this unscathed... so store the static user
        staticLogin.set(newUser);
    }

    // hadoop impersonation works with or without kerberos security
    proxyTicket = null;
    if (!proxyUserName.isEmpty()) {
        try {
            proxyTicket = UserGroupInformation.createProxyUser(proxyUserName,
                    UserGroupInformation.getLoginUser());
        } catch (IOException ex) {
            LOG.error("Unable to login as proxy user. Exception follows.", ex);
            return false;
        }
    }

    UserGroupInformation ugi = null;
    if (proxyTicket != null) {
        ugi = proxyTicket;
    } else if (useSecurity) {
        try {
            ugi = UserGroupInformation.getLoginUser();
        } catch (IOException ex) {
            LOG.error("Unexpected error: Unable to get authenticated user after "
                    + "apparent successful login! Exception follows.", ex);
            return false;
        }
    }

    if (ugi != null) {
        // dump login information
        AuthenticationMethod authMethod = ugi.getAuthenticationMethod();
        LOG.info("Auth method: {}", authMethod);
        LOG.info(" User name: {}", ugi.getUserName());
        LOG.info(" Using keytab: {}", ugi.isFromKeytab());
        if (authMethod == AuthenticationMethod.PROXY) {
            UserGroupInformation superUser;
            try {
                superUser = UserGroupInformation.getLoginUser();
                LOG.info(" Superuser auth: {}", superUser.getAuthenticationMethod());
                LOG.info(" Superuser name: {}", superUser.getUserName());
                LOG.info(" Superuser using keytab: {}", superUser.isFromKeytab());
            } catch (IOException ex) {
                LOG.error("Unexpected error: unknown superuser impersonating proxy.", ex);
                return false;
            }
        }

        LOG.info("Logged in as user {}", ugi.getUserName());

        return true;
    }

    return true;
}