Example usage for org.apache.hadoop.security HadoopKerberosName HadoopKerberosName

List of usage examples for org.apache.hadoop.security HadoopKerberosName HadoopKerberosName

Introduction

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

Prototype

public HadoopKerberosName(String name) 

Source Link

Document

Create a name from the full Kerberos principal name.

Usage

From source file:joshelser.Server.java

License:Apache License

public static void main(String[] args) throws Exception {
    Opts opts = new Opts();

    opts.parseArgs(Server.class, args);

    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(conf);

    // Parse out the primary/instance@DOMAIN from the principal
    String principal = SecurityUtil.getServerPrincipal(opts.principal,
            InetAddress.getLocalHost().getCanonicalHostName());
    HadoopKerberosName name = new HadoopKerberosName(principal);
    String primary = name.getServiceName();
    String instance = name.getHostName();

    // Log in using the keytab
    UserGroupInformation.loginUserFromKeytab(principal, opts.keytab);

    // Get the info from our login
    UserGroupInformation serverUser = UserGroupInformation.getLoginUser();
    log.info("Current user: {}", serverUser);

    // Open the server using the provide dport
    TServerSocket serverTransport = new TServerSocket(opts.port);

    // Wrap our implementation with the interface's processor
    HdfsService.Processor<Iface> processor = new HdfsService.Processor<Iface>(new HdfsServiceImpl(fs));

    // Use authorization and confidentiality
    Map<String, String> saslProperties = new HashMap<String, String>();
    saslProperties.put(Sasl.QOP, "auth-conf");

    // Creating the server definition
    TSaslServerTransport.Factory saslTransportFactory = new TSaslServerTransport.Factory();
    saslTransportFactory.addServerDefinition("GSSAPI", // tell SASL to use GSSAPI, which supports Kerberos
            primary, // kerberos primary for server - "myprincipal" in myprincipal/my.server.com@MY.REALM
            instance, // kerberos instance for server - "my.server.com" in myprincipal/my.server.com@MY.REALM
            saslProperties, // Properties set, above
            new SaslRpcServer.SaslGssCallbackHandler()); // Ensures that authenticated user is the same as the authorized user

    // Make sure the TTransportFactory is performing a UGI.doAs
    TTransportFactory ugiTransportFactory = new TUGIAssumingTransportFactory(saslTransportFactory, serverUser);

    // Processor which takes the UGI for the RPC call, proxy that user on the server login, and then run as the proxied user
    TUGIAssumingProcessor ugiProcessor = new TUGIAssumingProcessor(processor);

    // Make a simple TTheadPoolServer with the processor and transport factory
    TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport)
            .transportFactory(ugiTransportFactory).processor(ugiProcessor));

    // Start the thrift server
    server.serve();// w  w  w. j av a 2  s.  c om
}

From source file:org.apache.drill.exec.rpc.AbstractServerConnection.java

License:Apache License

@Override
public void finalizeSaslSession() throws IOException {
    final String authorizationID = getSaslServer().getAuthorizationID();
    final String remoteShortName = new HadoopKerberosName(authorizationID).getShortName();
    final String localShortName = UserGroupInformation.getLoginUser().getShortUserName();
    if (!localShortName.equals(remoteShortName)) {
        throw new SaslException(String.format(
                "'primary' part of remote drillbit's service principal "
                        + "does not match with this drillbit's. Expected: '%s' Actual: '%s'",
                localShortName, remoteShortName));
    }/*from   w  ww . j a  v  a2s.  c  o m*/
    getLogger().debug("Authenticated connection for {}", authorizationID);
}

From source file:org.apache.drill.exec.rpc.BitConnectionConfig.java

License:Apache License

public Map<String, ?> getSaslClientProperties(final DrillbitEndpoint remoteEndpoint) throws IOException {
    final DrillProperties properties = DrillProperties.createEmpty();

    final UserGroupInformation loginUser = UserGroupInformation.getLoginUser();
    if (loginUser.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.KERBEROS) {
        final HadoopKerberosName loginPrincipal = new HadoopKerberosName(loginUser.getUserName());
        if (!useLoginPrincipal) {
            properties.setProperty(DrillProperties.SERVICE_PRINCIPAL, KerberosUtil.getPrincipalFromParts(
                    loginPrincipal.getShortName(), remoteEndpoint.getAddress(), loginPrincipal.getRealm()));
        } else {//from  w  w  w.  j  a v a 2 s. c  om
            properties.setProperty(DrillProperties.SERVICE_PRINCIPAL, loginPrincipal.toString());
        }
    }
    return properties.stringPropertiesAsMap();
}

From source file:org.apache.drill.exec.rpc.security.kerberos.KerberosFactory.java

License:Apache License

@Override
public SaslServer createSaslServer(final UserGroupInformation ugi, final Map<String, ?> properties)
        throws SaslException {
    try {//from  w w  w .j  a v  a  2 s  . c  o m
        final String primaryName = ugi.getShortUserName();
        final String instanceName = new HadoopKerberosName(ugi.getUserName()).getHostName();

        final SaslServer saslServer = ugi.doAs(new PrivilegedExceptionAction<SaslServer>() {
            @Override
            public SaslServer run() throws Exception {
                return FastSaslServerFactory.getInstance().createSaslServer(KerberosUtil.KERBEROS_SASL_NAME,
                        primaryName, instanceName, properties, new KerberosServerCallbackHandler());
            }
        });
        logger.trace("GSSAPI SaslServer created.");
        return saslServer;
    } catch (final UndeclaredThrowableException e) {
        final Throwable cause = e.getCause();
        logger.debug("Authentication failed.", cause);
        if (cause instanceof SaslException) {
            throw (SaslException) cause;
        } else {
            throw new SaslException("Unexpected failure trying to authenticate using Kerberos", cause);
        }
    } catch (final IOException | InterruptedException e) {
        logger.debug("Authentication failed.", e);
        throw new SaslException("Unexpected failure trying to authenticate using Kerberos", e);
    }
}

From source file:org.apache.drill.exec.server.rest.auth.DrillSpnegoLoginService.java

License:Apache License

private UserIdentity spnegoLogin(Object credentials) {

    String encodedAuthToken = (String) credentials;
    byte[] authToken = B64Code.decode(encodedAuthToken);
    GSSManager manager = GSSManager.getInstance();

    try {//  ww  w  .j  a v a2 s.  c  om
        // Providing both OID's is required here. If we provide only one,
        // we're requiring that clients provide us the SPNEGO OID to authenticate via Kerberos.
        Oid[] knownOids = new Oid[2];
        knownOids[0] = new Oid("1.3.6.1.5.5.2"); // spnego
        knownOids[1] = new Oid("1.2.840.113554.1.2.2"); // kerberos

        GSSName gssName = manager.createName(spnegoConfig.getSpnegoPrincipal(), null);
        GSSCredential serverCreds = manager.createCredential(gssName, GSSCredential.INDEFINITE_LIFETIME,
                knownOids, GSSCredential.ACCEPT_ONLY);
        GSSContext gContext = manager.createContext(serverCreds);

        if (gContext == null) {
            logger.debug("SPNEGOUserRealm: failed to establish GSSContext");
        } else {
            while (!gContext.isEstablished()) {
                authToken = gContext.acceptSecContext(authToken, 0, authToken.length);
            }

            if (gContext.isEstablished()) {
                final String clientName = gContext.getSrcName().toString();
                final String realm = clientName.substring(clientName.indexOf(64) + 1);

                // Get the client user short name
                final String userShortName = new HadoopKerberosName(clientName).getShortName();

                logger.debug("Client Name: {}, realm: {} and shortName: {}", clientName, realm, userShortName);
                final SystemOptionManager sysOptions = drillContext.getOptionManager();
                final boolean isAdmin = ImpersonationUtil.hasAdminPrivileges(userShortName,
                        ExecConstants.ADMIN_USERS_VALIDATOR.getAdminUsers(sysOptions),
                        ExecConstants.ADMIN_USER_GROUPS_VALIDATOR.getAdminUserGroups(sysOptions));

                final Principal user = new DrillUserPrincipal(userShortName, isAdmin);
                final Subject subject = new Subject();
                subject.getPrincipals().add(user);

                if (isAdmin) {
                    return this._identityService.newUserIdentity(subject, user,
                            DrillUserPrincipal.ADMIN_USER_ROLES);
                } else {
                    return this._identityService.newUserIdentity(subject, user,
                            DrillUserPrincipal.NON_ADMIN_USER_ROLES);
                }
            }
        }
    } catch (GSSException gsse) {
        logger.warn("Caught GSSException trying to authenticate the client", gsse);
    } catch (IOException ex) {
        logger.warn("Caught IOException trying to get shortName of client user", ex);
    }
    return null;
}

From source file:org.apache.ranger.services.kms.client.KMSClient.java

License:Apache License

public List<String> getKeyList(final String keyNameMatching, final List<String> existingKeyList) {

    String providers[] = null;//  ww  w .  j a  va 2s.c o m
    try {
        providers = createProvider(provider);
    } catch (IOException | URISyntaxException e) {
        return null;
    }
    final String errMsg = errMessage;
    List<String> lret = null;
    for (int i = 0; i < providers.length; i++) {
        lret = new ArrayList<String>();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Getting Kms Key list for keyNameMatching : " + keyNameMatching);
        }
        String uri = providers[i]
                + (providers[i].endsWith("/") ? KMS_LIST_API_ENDPOINT : ("/" + KMS_LIST_API_ENDPOINT));
        Client client = null;
        ClientResponse response = null;
        boolean isKerberos = false;
        try {
            ClientConfig cc = new DefaultClientConfig();
            cc.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
            client = Client.create(cc);

            if (authType != null && authType.equalsIgnoreCase(AUTH_TYPE_KERBEROS)) {
                isKerberos = true;
            }

            Subject sub = new Subject();
            if (!isKerberos) {
                uri = uri.concat("?user.name=" + username);
                WebResource webResource = client.resource(uri);
                response = webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class);
                LOG.info("Init Login: security not enabled, using username");
                sub = SecureClientLogin.login(username);
            } else {
                if (!StringUtils.isEmpty(rangerPrincipal) && !StringUtils.isEmpty(rangerKeytab)) {
                    LOG.info("Init Lookup Login: security enabled, using rangerPrincipal/rangerKeytab");
                    if (StringUtils.isEmpty(nameRules)) {
                        nameRules = "DEFAULT";
                    }
                    String shortName = new HadoopKerberosName(rangerPrincipal).getShortName();
                    uri = uri.concat("?doAs=" + shortName);
                    sub = SecureClientLogin.loginUserFromKeytab(rangerPrincipal, rangerKeytab, nameRules);
                } else {
                    LOG.info("Init Login: using username/password");
                    String shortName = new HadoopKerberosName(username).getShortName();
                    uri = uri.concat("?doAs=" + shortName);
                    String decryptedPwd = PasswordUtils.decryptPassword(password);
                    sub = SecureClientLogin.loginUserWithPassword(username, decryptedPwd);
                }
            }
            final WebResource webResource = client.resource(uri);
            response = Subject.doAs(sub, new PrivilegedAction<ClientResponse>() {
                @Override
                public ClientResponse run() {
                    return webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class);
                }
            });

            if (LOG.isDebugEnabled()) {
                LOG.debug("getKeyList():calling " + uri);
            }
            if (response != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("getKeyList():response.getStatus()= " + response.getStatus());
                }
                if (response.getStatus() == 200) {
                    String jsonString = response.getEntity(String.class);
                    Gson gson = new GsonBuilder().setPrettyPrinting().create();
                    @SuppressWarnings("unchecked")
                    List<String> keys = gson.fromJson(jsonString, List.class);
                    if (keys != null) {
                        for (String key : keys) {
                            if (existingKeyList != null && existingKeyList.contains(key)) {
                                continue;
                            }
                            if (keyNameMatching == null || keyNameMatching.isEmpty()
                                    || key.startsWith(keyNameMatching)) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("getKeyList():Adding kmsKey " + key);
                                }
                                lret.add(key);
                            }
                        }
                        return lret;
                    }
                } else if (response.getStatus() == 401) {
                    LOG.info("getKeyList():response.getStatus()= " + response.getStatus() + " for URL " + uri
                            + ", so returning null list");
                    String msgDesc = response.getEntity(String.class);
                    HadoopException hdpException = new HadoopException(msgDesc);
                    hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null);
                    lret = null;
                    throw hdpException;
                } else if (response.getStatus() == 403) {
                    LOG.info("getKeyList():response.getStatus()= " + response.getStatus() + " for URL " + uri
                            + ", so returning null list");
                    String msgDesc = response.getEntity(String.class);
                    HadoopException hdpException = new HadoopException(msgDesc);
                    hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null);
                    lret = null;
                    throw hdpException;
                } else {
                    LOG.info("getKeyList():response.getStatus()= " + response.getStatus() + " for URL " + uri
                            + ", so returning null list");
                    String jsonString = response.getEntity(String.class);
                    LOG.info(jsonString);
                    lret = null;
                }
            } else {
                String msgDesc = "Unable to get a valid response for " + "expected mime type : ["
                        + EXPECTED_MIME_TYPE + "] URL : " + uri + " - got null response.";
                LOG.error(msgDesc);
                HadoopException hdpException = new HadoopException(msgDesc);
                hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null);
                lret = null;
                throw hdpException;
            }
        } catch (HadoopException he) {
            lret = null;
            throw he;
        } catch (Throwable t) {
            String msgDesc = "Exception while getting Kms Key List. URL : " + uri;
            HadoopException hdpException = new HadoopException(msgDesc, t);
            LOG.error(msgDesc, t);
            hdpException.generateResponseDataMap(false, BaseClient.getMessage(t), msgDesc + errMsg, null, null);
            lret = null;
            throw hdpException;
        } finally {
            if (response != null) {
                response.close();
            }

            if (client != null) {
                client.destroy();
            }

            if (lret == null) {
                if (i != providers.length - 1)
                    continue;
            }
        }
    }
    return lret;
}