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

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

Introduction

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

Prototype

@InterfaceAudience.Public
@InterfaceStability.Evolving
public String getUserName() 

Source Link

Document

Get the user's full principal name.

Usage

From source file:org.apache.accumulo.server.rpc.SaslServerDigestCallbackHandler.java

License:Apache License

@Override
public void handle(Callback[] callbacks) throws InvalidToken, UnsupportedCallbackException {
    NameCallback nc = null;//w  ww  .ja v a2 s.c om
    PasswordCallback pc = null;
    AuthorizeCallback ac = null;
    for (Callback callback : callbacks) {
        if (callback instanceof AuthorizeCallback) {
            ac = (AuthorizeCallback) callback;
        } else if (callback instanceof NameCallback) {
            nc = (NameCallback) callback;
        } else if (callback instanceof PasswordCallback) {
            pc = (PasswordCallback) callback;
        } else if (callback instanceof RealmCallback) {
            continue; // realm is ignored
        } else {
            throw new UnsupportedCallbackException(callback, "Unrecognized SASL DIGEST-MD5 Callback");
        }
    }

    if (pc != null) {
        AuthenticationTokenIdentifier tokenIdentifier = getIdentifier(nc.getDefaultName(), secretManager);
        char[] password = getPassword(secretManager, tokenIdentifier);
        UserGroupInformation user = null;
        user = tokenIdentifier.getUser();

        // Set the principal since we already deserialized the token identifier
        UGIAssumingProcessor.getRpcPrincipalThreadLocal().set(user.getUserName());

        log.trace("SASL server DIGEST-MD5 callback: setting password for client: {}",
                tokenIdentifier.getUser());
        pc.setPassword(password);
    }
    if (ac != null) {
        String authid = ac.getAuthenticationID();
        String authzid = ac.getAuthorizationID();
        if (authid.equals(authzid)) {
            ac.setAuthorized(true);
        } else {
            ac.setAuthorized(false);
        }
        if (ac.isAuthorized()) {
            String username = getIdentifier(authzid, secretManager).getUser().getUserName();
            log.trace("SASL server DIGEST-MD5 callback: setting canonicalized client ID: {}", username);
            ac.setAuthorizedID(authzid);
        }
    }
}

From source file:org.apache.accumulo.server.rpc.UGIAssumingProcessor.java

License:Apache License

@Override
public boolean process(final TProtocol inProt, final TProtocol outProt) throws TException {
    TTransport trans = inProt.getTransport();
    if (!(trans instanceof TSaslServerTransport)) {
        throw new TException("Unexpected non-SASL transport " + trans.getClass() + ": " + trans);
    }//  w  w w  . j a  v a 2  s  . c  o  m
    TSaslServerTransport saslTrans = (TSaslServerTransport) trans;
    SaslServer saslServer = saslTrans.getSaslServer();
    String authId = saslServer.getAuthorizationID();
    String endUser = authId;

    SaslMechanism mechanism;
    try {
        mechanism = SaslMechanism.get(saslServer.getMechanismName());
    } catch (Exception e) {
        log.error("Failed to process RPC with SASL mechanism {}", saslServer.getMechanismName());
        throw e;
    }

    switch (mechanism) {
    case GSSAPI:
        UserGroupInformation clientUgi = UserGroupInformation.createProxyUser(endUser, loginUser);
        final String remoteUser = clientUgi.getUserName();

        try {
            // Set the principal in the ThreadLocal for access to get authorizations
            rpcPrincipal.set(remoteUser);

            return wrapped.process(inProt, outProt);
        } finally {
            // Unset the principal after we're done using it just to be sure that it's not incorrectly
            // used in the same thread down the line.
            rpcPrincipal.set(null);
        }
    case DIGEST_MD5:
        // The CallbackHandler, after deserializing the TokenIdentifier in the name, has already updated
        // the rpcPrincipal for us. We don't need to do it again here.
        try {
            rpcMechanism.set(mechanism);
            return wrapped.process(inProt, outProt);
        } finally {
            // Unset the mechanism after we're done using it just to be sure that it's not incorrectly
            // used in the same thread down the line.
            rpcMechanism.set(null);
        }
    default:
        throw new IllegalArgumentException("Cannot process SASL mechanism " + mechanism);
    }
}

From source file:org.apache.accumulo.server.ServerContext.java

License:Apache License

/**
 * A "client-side" assertion for servers to validate that they are logged in as the expected user,
 * per the configuration, before performing any RPC
 *//*from   www.j av  a  2  s  .  co  m*/
// Should be private, but package-protected so EasyMock will work
void enforceKerberosLogin() {
    final AccumuloConfiguration conf = getServerConfFactory().getSiteConfiguration();
    // Unwrap _HOST into the FQDN to make the kerberos principal we'll compare against
    final String kerberosPrincipal = SecurityUtil
            .getServerPrincipal(conf.get(Property.GENERAL_KERBEROS_PRINCIPAL));
    UserGroupInformation loginUser;
    try {
        // The system user should be logged in via keytab when the process is started, not the
        // currentUser() like KerberosToken
        loginUser = UserGroupInformation.getLoginUser();
    } catch (IOException e) {
        throw new RuntimeException("Could not get login user", e);
    }

    checkArgument(loginUser.hasKerberosCredentials(), "Server does not have Kerberos credentials");
    checkArgument(kerberosPrincipal.equals(loginUser.getUserName()),
            "Expected login user to be " + kerberosPrincipal + " but was " + loginUser.getUserName());
}

From source file:org.apache.accumulo.shell.ShellOptionsJC.java

License:Apache License

public String getUsername() throws Exception {
    if (null == username) {
        final ClientConfiguration clientConf = getClientConfiguration();
        if (Boolean.parseBoolean(clientConf.get(ClientProperty.INSTANCE_RPC_SASL_ENABLED))) {
            if (!UserGroupInformation.isSecurityEnabled()) {
                throw new RuntimeException("Kerberos security is not enabled");
            }/*  w  w  w .  java2 s .  c  o m*/
            UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
            username = ugi.getUserName();
        } else {
            username = System.getProperty("user.name", "root");
        }
    }
    return username;
}

From source file:org.apache.accumulo.test.randomwalk.multitable.CopyTool.java

License:Apache License

@Override
public int run(String[] args) throws Exception {
    Job job = Job.getInstance(getConf(), this.getClass().getSimpleName());
    job.setJarByClass(this.getClass());

    if (job.getJar() == null) {
        log.error("M/R requires a jar file!  Run mvn package.");
        return 1;
    }/*  w w w  . j  a va 2  s  . co  m*/

    ClientConfiguration clientConf = new ClientConfiguration().withInstance(args[3]).withZkHosts(args[4]);

    job.setInputFormatClass(AccumuloInputFormat.class);
    AccumuloInputFormat.setInputTableName(job, args[2]);
    AccumuloInputFormat.setScanAuthorizations(job, Authorizations.EMPTY);
    AccumuloInputFormat.setZooKeeperInstance(job, clientConf);

    final String principal;
    final AuthenticationToken token;
    if (clientConf.getBoolean(ClientProperty.INSTANCE_RPC_SASL_ENABLED.getKey(), false)) {
        // Use the Kerberos creds to request a DelegationToken for MapReduce to use
        // We could use the specified keytab (args[1]), but we're already logged in and don't need to, so we can just use the current user
        KerberosToken kt = new KerberosToken();
        try {
            UserGroupInformation user = UserGroupInformation.getCurrentUser();
            if (!user.hasKerberosCredentials()) {
                throw new IllegalStateException("Expected current user to have Kerberos credentials");
            }

            // Get the principal via UGI
            principal = user.getUserName();

            // Connector w/ the Kerberos creds
            ZooKeeperInstance inst = new ZooKeeperInstance(clientConf);
            Connector conn = inst.getConnector(principal, kt);

            // Do the explicit check to see if the user has the permission to get a delegation token
            if (!conn.securityOperations().hasSystemPermission(conn.whoami(),
                    SystemPermission.OBTAIN_DELEGATION_TOKEN)) {
                log.error(principal + " doesn't have the " + SystemPermission.OBTAIN_DELEGATION_TOKEN.name()
                        + " SystemPermission neccesary to obtain a delegation token. MapReduce tasks cannot automatically use the client's"
                        + " credentials on remote servers. Delegation tokens provide a means to run MapReduce without distributing the user's credentials.");
                throw new IllegalStateException(
                        conn.whoami() + " does not have permission to obtain a delegation token");
            }

            // Fetch a delegation token from Accumulo
            token = conn.securityOperations().getDelegationToken(new DelegationTokenConfig());

        } catch (Exception e) {
            final String msg = "Failed to acquire DelegationToken for use with MapReduce";
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        }
    } else {
        // Simple principal + password
        principal = args[0];
        token = new PasswordToken(args[1]);
    }

    AccumuloInputFormat.setConnectorInfo(job, principal, token);
    AccumuloOutputFormat.setConnectorInfo(job, principal, token);

    job.setMapperClass(SeqMapClass.class);
    job.setMapOutputKeyClass(Text.class);
    job.setMapOutputValueClass(Mutation.class);

    job.setNumReduceTasks(0);

    job.setOutputFormatClass(AccumuloOutputFormat.class);
    AccumuloOutputFormat.setCreateTables(job, true);
    AccumuloOutputFormat.setDefaultTableName(job, args[5]);
    AccumuloOutputFormat.setZooKeeperInstance(job, clientConf);

    job.waitForCompletion(true);
    return job.isSuccessful() ? 0 : 1;
}

From source file:org.apache.accumulo.test.randomwalk.sequential.MapRedVerifyTool.java

License:Apache License

@Override
public int run(String[] args) throws Exception {
    Job job = Job.getInstance(getConf(), this.getClass().getSimpleName());
    job.setJarByClass(this.getClass());

    if (job.getJar() == null) {
        log.error("M/R requires a jar file!  Run mvn package.");
        return 1;
    }//from   ww w  .  j a  v a 2s.c  o m

    ClientConfiguration clientConf = ClientConfiguration.loadDefault().withInstance(args[3])
            .withZkHosts(args[4]);

    AccumuloInputFormat.setInputTableName(job, args[2]);
    AccumuloInputFormat.setZooKeeperInstance(job, clientConf);
    AccumuloOutputFormat.setDefaultTableName(job, args[5]);
    AccumuloOutputFormat.setZooKeeperInstance(job, clientConf);

    job.setInputFormatClass(AccumuloInputFormat.class);
    if (clientConf.getBoolean(ClientProperty.INSTANCE_RPC_SASL_ENABLED.getKey(), false)) {
        // Better be logged in
        KerberosToken token = new KerberosToken();
        try {
            UserGroupInformation user = UserGroupInformation.getCurrentUser();
            if (!user.hasKerberosCredentials()) {
                throw new IllegalStateException("Expected current user to have Kerberos credentials");
            }

            String newPrincipal = user.getUserName();

            ZooKeeperInstance inst = new ZooKeeperInstance(clientConf);
            Connector conn = inst.getConnector(newPrincipal, token);

            // Do the explicit check to see if the user has the permission to get a delegation token
            if (!conn.securityOperations().hasSystemPermission(conn.whoami(),
                    SystemPermission.OBTAIN_DELEGATION_TOKEN)) {
                log.error(newPrincipal + " doesn't have the " + SystemPermission.OBTAIN_DELEGATION_TOKEN.name()
                        + " SystemPermission neccesary to obtain a delegation token. MapReduce tasks cannot automatically use the client's"
                        + " credentials on remote servers. Delegation tokens provide a means to run MapReduce without distributing the user's credentials.");
                throw new IllegalStateException(
                        conn.whoami() + " does not have permission to obtain a delegation token");
            }

            // Fetch a delegation token from Accumulo
            AuthenticationToken dt = conn.securityOperations().getDelegationToken(new DelegationTokenConfig());

            // Set the delegation token instead of the kerberos token
            AccumuloInputFormat.setConnectorInfo(job, newPrincipal, dt);
            AccumuloOutputFormat.setConnectorInfo(job, newPrincipal, dt);
        } catch (Exception e) {
            final String msg = "Failed to acquire DelegationToken for use with MapReduce";
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        }
    } else {
        AccumuloInputFormat.setConnectorInfo(job, args[0], new PasswordToken(args[1]));
        AccumuloOutputFormat.setConnectorInfo(job, args[0], new PasswordToken(args[1]));
    }

    job.setMapperClass(SeqMapClass.class);
    job.setMapOutputKeyClass(NullWritable.class);
    job.setMapOutputValueClass(IntWritable.class);

    job.setReducerClass(SeqReduceClass.class);
    job.setNumReduceTasks(1);

    job.setOutputFormatClass(AccumuloOutputFormat.class);
    AccumuloOutputFormat.setCreateTables(job, true);

    job.waitForCompletion(true);
    return job.isSuccessful() ? 0 : 1;
}

From source file:org.apache.accumulo.test.security.KerberosClientOptsTest.java

License:Apache License

@Test
public void testParseArgsPerformsLogin() throws Exception {
    String user = testName.getMethodName();
    File userKeytab = new File(kdc.getKeytabDir(), user + ".keytab");
    if (userKeytab.exists() && !userKeytab.delete()) {
        log.warn("Unable to delete {}", userKeytab);
    }/*from   ww w.j av  a2  s .c  o m*/

    kdc.createPrincipal(userKeytab, user);

    user = kdc.qualifyUser(user);

    ClientOpts opts = new ClientOpts();
    String[] args = new String[] { "--sasl", "--keytab", userKeytab.getAbsolutePath(), "-u", user };
    opts.parseArgs(testName.getMethodName(), args);

    UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
    assertEquals(user, ugi.getUserName());
    assertEquals(AuthenticationMethod.KERBEROS, ugi.getAuthenticationMethod());
}

From source file:org.apache.accumulo.testing.core.randomwalk.multitable.CopyTool.java

License:Apache License

@Override
public int run(String[] args) throws Exception {
    Job job = Job.getInstance(getConf(), this.getClass().getSimpleName());
    job.setJarByClass(this.getClass());

    if (job.getJar() == null) {
        log.error("M/R requires a jar file!  Run mvn package.");
        return 1;
    }/*from w w w .j  ava  2s .  co  m*/

    ClientConfiguration clientConf = new ClientConfiguration().withInstance(args[3]).withZkHosts(args[4]);

    job.setInputFormatClass(AccumuloInputFormat.class);
    AccumuloInputFormat.setInputTableName(job, args[2]);
    AccumuloInputFormat.setScanAuthorizations(job, Authorizations.EMPTY);
    AccumuloInputFormat.setZooKeeperInstance(job, clientConf);

    final String principal;
    final AuthenticationToken token;
    if (clientConf.getBoolean(ClientProperty.INSTANCE_RPC_SASL_ENABLED.getKey(), false)) {
        // Use the Kerberos creds to request a DelegationToken for MapReduce
        // to use
        // We could use the specified keytab (args[1]), but we're already
        // logged in and don't need to, so we can just use the current user
        KerberosToken kt = new KerberosToken();
        try {
            UserGroupInformation user = UserGroupInformation.getCurrentUser();
            if (!user.hasKerberosCredentials()) {
                throw new IllegalStateException("Expected current user to have Kerberos credentials");
            }

            // Get the principal via UGI
            principal = user.getUserName();

            // Connector w/ the Kerberos creds
            ZooKeeperInstance inst = new ZooKeeperInstance(clientConf);
            Connector conn = inst.getConnector(principal, kt);

            // Do the explicit check to see if the user has the permission
            // to get a delegation token
            if (!conn.securityOperations().hasSystemPermission(conn.whoami(),
                    SystemPermission.OBTAIN_DELEGATION_TOKEN)) {
                log.error(principal + " doesn't have the " + SystemPermission.OBTAIN_DELEGATION_TOKEN.name()
                        + " SystemPermission neccesary to obtain a delegation token. MapReduce tasks cannot automatically use the client's"
                        + " credentials on remote servers. Delegation tokens provide a means to run MapReduce without distributing the user's credentials.");
                throw new IllegalStateException(
                        conn.whoami() + " does not have permission to obtain a delegation token");
            }

            // Fetch a delegation token from Accumulo
            token = conn.securityOperations().getDelegationToken(new DelegationTokenConfig());

        } catch (Exception e) {
            final String msg = "Failed to acquire DelegationToken for use with MapReduce";
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        }
    } else {
        // Simple principal + password
        principal = args[0];
        token = new PasswordToken(args[1]);
    }

    AccumuloInputFormat.setConnectorInfo(job, principal, token);
    AccumuloOutputFormat.setConnectorInfo(job, principal, token);

    job.setMapperClass(SeqMapClass.class);
    job.setMapOutputKeyClass(Text.class);
    job.setMapOutputValueClass(Mutation.class);

    job.setNumReduceTasks(0);

    job.setOutputFormatClass(AccumuloOutputFormat.class);
    AccumuloOutputFormat.setCreateTables(job, true);
    AccumuloOutputFormat.setDefaultTableName(job, args[5]);
    AccumuloOutputFormat.setZooKeeperInstance(job, clientConf);

    job.waitForCompletion(true);
    return job.isSuccessful() ? 0 : 1;
}

From source file:org.apache.accumulo.testing.core.randomwalk.sequential.MapRedVerifyTool.java

License:Apache License

@Override
public int run(String[] args) throws Exception {
    Job job = Job.getInstance(getConf(), this.getClass().getSimpleName());
    job.setJarByClass(this.getClass());

    if (job.getJar() == null) {
        log.error("M/R requires a jar file!  Run mvn package.");
        return 1;
    }/* w w  w .j a  v a 2 s  .c  o  m*/

    ClientConfiguration clientConf = ClientConfiguration.loadDefault().withInstance(args[3])
            .withZkHosts(args[4]);

    AccumuloInputFormat.setInputTableName(job, args[2]);
    AccumuloInputFormat.setZooKeeperInstance(job, clientConf);
    AccumuloOutputFormat.setDefaultTableName(job, args[5]);
    AccumuloOutputFormat.setZooKeeperInstance(job, clientConf);

    job.setInputFormatClass(AccumuloInputFormat.class);
    if (clientConf.getBoolean(ClientProperty.INSTANCE_RPC_SASL_ENABLED.getKey(), false)) {
        // Better be logged in
        KerberosToken token = new KerberosToken();
        try {
            UserGroupInformation user = UserGroupInformation.getCurrentUser();
            if (!user.hasKerberosCredentials()) {
                throw new IllegalStateException("Expected current user to have Kerberos credentials");
            }

            String newPrincipal = user.getUserName();

            ZooKeeperInstance inst = new ZooKeeperInstance(clientConf);
            Connector conn = inst.getConnector(newPrincipal, token);

            // Do the explicit check to see if the user has the permission
            // to get a delegation token
            if (!conn.securityOperations().hasSystemPermission(conn.whoami(),
                    SystemPermission.OBTAIN_DELEGATION_TOKEN)) {
                log.error(newPrincipal + " doesn't have the " + SystemPermission.OBTAIN_DELEGATION_TOKEN.name()
                        + " SystemPermission neccesary to obtain a delegation token. MapReduce tasks cannot automatically use the client's"
                        + " credentials on remote servers. Delegation tokens provide a means to run MapReduce without distributing the user's credentials.");
                throw new IllegalStateException(
                        conn.whoami() + " does not have permission to obtain a delegation token");
            }

            // Fetch a delegation token from Accumulo
            AuthenticationToken dt = conn.securityOperations().getDelegationToken(new DelegationTokenConfig());

            // Set the delegation token instead of the kerberos token
            AccumuloInputFormat.setConnectorInfo(job, newPrincipal, dt);
            AccumuloOutputFormat.setConnectorInfo(job, newPrincipal, dt);
        } catch (Exception e) {
            final String msg = "Failed to acquire DelegationToken for use with MapReduce";
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        }
    } else {
        AccumuloInputFormat.setConnectorInfo(job, args[0], new PasswordToken(args[1]));
        AccumuloOutputFormat.setConnectorInfo(job, args[0], new PasswordToken(args[1]));
    }

    job.setMapperClass(SeqMapClass.class);
    job.setMapOutputKeyClass(NullWritable.class);
    job.setMapOutputValueClass(IntWritable.class);

    job.setReducerClass(SeqReduceClass.class);
    job.setNumReduceTasks(1);

    job.setOutputFormatClass(AccumuloOutputFormat.class);
    AccumuloOutputFormat.setCreateTables(job, true);

    job.waitForCompletion(true);
    return job.isSuccessful() ? 0 : 1;
}

From source file:org.apache.blur.hive.BlurHiveOutputFormat.java

License:Apache License

public static UserGroupInformation getUGI(final Configuration configuration) throws IOException {
    String user = getBlurUser(configuration);
    UserGroupInformation userGroupInformation;
    UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
    if (user.equals(currentUser.getUserName())) {
        userGroupInformation = currentUser;
    } else {/*  ww w.j av a  2  s . co m*/
        if (BlurHiveOutputFormat.isBlurUserAsProxy(configuration)) {
            userGroupInformation = UserGroupInformation.createProxyUser(user, currentUser);
        } else {
            userGroupInformation = UserGroupInformation.createRemoteUser(user);
        }
    }
    return userGroupInformation;
}