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

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

Introduction

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

Prototype

@InterfaceAudience.Public
@InterfaceStability.Evolving
public UserGroupInformation getRealUser() 

Source Link

Document

get RealUser (vs.

Usage

From source file:com.cloudera.impala.security.DelegationTokenSecretManager.java

License:Apache License

public synchronized String getDelegationToken(String renewer) throws IOException {
    UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
    Text owner = new Text(ugi.getUserName());
    Text realUser = null;/*  w  w w.j  a  va  2  s . co  m*/
    if (ugi.getRealUser() != null) {
        realUser = new Text(ugi.getRealUser().getUserName());
    }
    DelegationTokenIdentifier ident = new DelegationTokenIdentifier(owner, new Text(renewer), realUser);
    Token<DelegationTokenIdentifier> t = new Token<DelegationTokenIdentifier>(ident, this);
    LOGGER.info("Generated delegation token. Identifer=" + ident);
    return t.encodeToUrlString();
}

From source file:gobblin.compliance.utils.ProxyUtils.java

License:Apache License

public static void cancelTokens(State state) throws IOException, InterruptedException, TException {
    Preconditions.checkArgument(state.contains(ConfigurationKeys.SUPER_USER_KEY_TAB_LOCATION),
            "Missing required property " + ConfigurationKeys.SUPER_USER_KEY_TAB_LOCATION);
    Preconditions.checkArgument(state.contains(ComplianceConfigurationKeys.GOBBLIN_COMPLIANCE_SUPER_USER),
            "Missing required property " + ComplianceConfigurationKeys.GOBBLIN_COMPLIANCE_SUPER_USER);
    Preconditions.checkArgument(state.contains(ConfigurationKeys.KERBEROS_REALM),
            "Missing required property " + ConfigurationKeys.KERBEROS_REALM);

    String superUser = state.getProp(ComplianceConfigurationKeys.GOBBLIN_COMPLIANCE_SUPER_USER);
    String keytabLocation = state.getProp(ConfigurationKeys.SUPER_USER_KEY_TAB_LOCATION);
    String realm = state.getProp(ConfigurationKeys.KERBEROS_REALM);

    UserGroupInformation.loginUserFromKeytab(HostUtils.getPrincipalUsingHostname(superUser, realm),
            keytabLocation);/*from  w  ww.ja  va 2 s  . co  m*/
    UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
    UserGroupInformation realUser = currentUser.getRealUser();
    Credentials credentials = realUser.getCredentials();
    for (Token<?> token : credentials.getAllTokens()) {
        if (token.getKind().equals(DelegationTokenIdentifier.HIVE_DELEGATION_KIND)) {
            log.info("Cancelling hive token");
            HiveMetaStoreClient hiveClient = new HiveMetaStoreClient(new HiveConf());
            hiveClient.cancelDelegationToken(token.encodeToUrlString());
        }
    }
}

From source file:org.apache.accumulo.core.rpc.ThriftUtil.java

License:Apache License

/**
 * Some wonderful snippets of documentation from HBase on performing the re-login client-side (as well as server-side) in the following paragraph. We want to
 * attempt a re-login to automatically refresh the client's Krb "credentials" (remember, a server might also be a client, master sending RPC to tserver), but
 * we have to take care to avoid Kerberos' replay attack protection.
 * <p>//from w w w.j a va2 s  . com
 * If multiple clients with the same principal try to connect to the same server at the same time, the server assumes a replay attack is in progress. This is
 * a feature of kerberos. In order to work around this, what is done is that the client backs off randomly and tries to initiate the connection again. The
 * other problem is to do with ticket expiry. To handle that, a relogin is attempted.
 */
static void attemptClientReLogin() {
    try {
        UserGroupInformation loginUser = UserGroupInformation.getLoginUser();
        if (null == loginUser || !loginUser.hasKerberosCredentials()) {
            // We should have already checked that we're logged in and have credentials. A precondition-like check.
            throw new RuntimeException("Expected to find Kerberos UGI credentials, but did not");
        }
        UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
        // A Proxy user is the "effective user" (in name only), riding on top of the "real user"'s Krb credentials.
        UserGroupInformation realUser = currentUser.getRealUser();

        // re-login only in case it is the login user or superuser.
        if (loginUser.equals(currentUser) || loginUser.equals(realUser)) {
            if (UserGroupInformation.isLoginKeytabBased()) {
                log.info("Performing keytab-based Kerberos re-login");
                loginUser.reloginFromKeytab();
            } else {
                log.info("Performing ticket-cache-based Kerberos re-login");
                loginUser.reloginFromTicketCache();
            }

            // Avoid the replay attack protection, sleep 1 to 5000ms
            try {
                Thread.sleep((SASL_BACKOFF_RAND.nextInt(RELOGIN_MAX_BACKOFF) + 1));
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
        } else {
            log.debug("Not attempting Kerberos re-login: loginUser={}, currentUser={}, realUser={}", loginUser,
                    currentUser, realUser);
        }
    } catch (IOException e) {
        // The inability to check is worrisome and deserves a RuntimeException instead of a propagated IO-like Exception.
        log.warn("Failed to check (and/or perform) Kerberos client re-login", e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.atlas.security.SecureClientUtils.java

License:Apache License

public static URLConnectionClientHandler getClientConnectionHandler(DefaultClientConfig config,
        org.apache.commons.configuration.Configuration clientConfig, String doAsUser,
        final UserGroupInformation ugi) {
    config.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND,
            true);/*  w  ww . ja va 2  s .c o  m*/
    Configuration conf = new Configuration();
    conf.addResource(conf.get(SSLFactory.SSL_CLIENT_CONF_KEY, SecurityProperties.SSL_CLIENT_PROPERTIES));
    UserGroupInformation.setConfiguration(conf);
    final ConnectionConfigurator connConfigurator = newConnConfigurator(conf);
    String authType = "simple";
    if (clientConfig != null) {
        authType = clientConfig.getString("atlas.http.authentication.type", "simple");
    }
    Authenticator authenticator = new PseudoDelegationTokenAuthenticator();
    if (!authType.equals("simple")) {
        authenticator = new KerberosDelegationTokenAuthenticator();
    }
    authenticator.setConnectionConfigurator(connConfigurator);
    final DelegationTokenAuthenticator finalAuthenticator = (DelegationTokenAuthenticator) authenticator;
    final DelegationTokenAuthenticatedURL.Token token = new DelegationTokenAuthenticatedURL.Token();
    HttpURLConnectionFactory httpURLConnectionFactory = null;
    try {
        UserGroupInformation ugiToUse = ugi != null ? ugi : UserGroupInformation.getCurrentUser();
        final UserGroupInformation actualUgi = (ugiToUse
                .getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.PROXY)
                        ? ugiToUse.getRealUser()
                        : ugiToUse;
        LOG.info("Real User: {}, is from ticket cache? {}", actualUgi, actualUgi.isLoginTicketBased());
        if (StringUtils.isEmpty(doAsUser)) {
            doAsUser = actualUgi.getShortUserName();
        }
        LOG.info("doAsUser: {}", doAsUser);
        final String finalDoAsUser = doAsUser;
        httpURLConnectionFactory = new HttpURLConnectionFactory() {
            @Override
            public HttpURLConnection getHttpURLConnection(final URL url) throws IOException {
                try {
                    return actualUgi.doAs(new PrivilegedExceptionAction<HttpURLConnection>() {
                        @Override
                        public HttpURLConnection run() throws Exception {
                            try {
                                return new DelegationTokenAuthenticatedURL(finalAuthenticator, connConfigurator)
                                        .openConnection(url, token, finalDoAsUser);
                            } catch (Exception e) {
                                throw new IOException(e);
                            }
                        }
                    });
                } catch (Exception e) {
                    if (e instanceof IOException) {
                        throw (IOException) e;
                    } else {
                        throw new IOException(e);
                    }
                }
            }
        };
    } catch (IOException e) {
        LOG.warn("Error obtaining user", e);
    }

    return new URLConnectionClientHandler(httpURLConnectionFactory);
}

From source file:org.apache.hive.hcatalog.templeton.tool.TempletonControllerJob.java

License:Apache License

private String buildHcatDelegationToken(String user) throws IOException, InterruptedException, TException {
    final HiveConf c = new HiveConf();
    LOG.debug("Creating hive metastore delegation token for user " + user);
    final UserGroupInformation ugi = UgiFactory.getUgi(user);
    UserGroupInformation real = ugi.getRealUser();
    return real.doAs(new PrivilegedExceptionAction<String>() {
        @Override//  ww w  .  j av a2  s .c o m
        public String run() throws IOException, TException, InterruptedException {
            final IMetaStoreClient client = HCatUtil.getHiveMetastoreClient(c);
            return ugi.doAs(new PrivilegedExceptionAction<String>() {
                @Override
                public String run() throws IOException, TException, InterruptedException {
                    String u = ugi.getUserName();
                    return client.getDelegationToken(c.getUser(), u);
                }
            });
        }
    });
}

From source file:org.apache.phoenix.queryserver.server.PhoenixDoAsCallbackTest.java

License:Apache License

@Test
public void ugiInstancesAreCached() throws Exception {
    Configuration conf = new Configuration(false);
    UserGroupInformation serverUgi = UserGroupInformation.createUserForTesting("server", new String[0]);
    PhoenixDoAsCallback callback = new PhoenixDoAsCallback(serverUgi, conf);

    UserGroupInformation ugi1 = callback.createProxyUser("user1");
    assertEquals(1, callback.getCache().size());
    assertTrue(ugi1.getRealUser() == serverUgi);
    UserGroupInformation ugi2 = callback.createProxyUser("user2");
    assertEquals(2, callback.getCache().size());
    assertTrue(ugi2.getRealUser() == serverUgi);

    UserGroupInformation ugi1Reference = callback.createProxyUser("user1");
    assertTrue(ugi1 == ugi1Reference);
    assertEquals(2, callback.getCache().size());
}

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//  www .  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:skewtune.mapreduce.STJobTracker.java

License:Apache License

/**
 * Get a new delegation token./*from  w ww  . j  a v a 2 s .com*/
 */
@Override
public Token<DelegationTokenIdentifier> getDelegationToken(Text renewer)
        throws IOException, InterruptedException {
    UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
    Text owner = new Text(ugi.getUserName());
    Text realUser = null;
    if (ugi.getRealUser() != null) {
        realUser = new Text(ugi.getRealUser().getUserName());
    }
    DelegationTokenIdentifier ident = new DelegationTokenIdentifier(owner, renewer, realUser);
    return new Token<DelegationTokenIdentifier>(ident, secretManager);
}