Java Code Examples for org.apache.hadoop.security.SecurityUtil#getServerPrincipal()

The following examples show how to use org.apache.hadoop.security.SecurityUtil#getServerPrincipal() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SecureLogin.java    From pxf with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the service principal name from the configuration if available,
 * or defaults to the system property for the default server for backwards
 * compatibility. If the prncipal name contains _HOST element, replaces it with the
 * name of the host where the service is running.
 *
 * @param serverName    the name of the server
 * @param configuration the hadoop configuration
 * @return the service principal for the given server and configuration
 */
String getServicePrincipal(String serverName, Configuration configuration) {
    // use system property as default for backward compatibility when only 1 Kerberized cluster was supported
    String defaultPrincipal = StringUtils.equalsIgnoreCase(serverName, "default") ?
            System.getProperty(CONFIG_KEY_SERVICE_PRINCIPAL) :
            null;
    String principal = configuration.get(CONFIG_KEY_SERVICE_PRINCIPAL, defaultPrincipal);
    try {
        principal = SecurityUtil.getServerPrincipal(principal, getLocalHostName(configuration));
        LOG.debug("Resolved Kerberos principal name to {} for server {}", principal, serverName);
        return principal;
    } catch (Exception e) {
        throw new IllegalStateException(
            String.format("Failed to determine local hostname for server {} : {}", serverName, e.getMessage()), e);
    }
}
 
Example 2
Source File: AtlasTopicCreator.java    From atlas with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
protected boolean handleSecurity(Configuration atlasProperties) {
    if (AuthenticationUtil.isKerberosAuthenticationEnabled(atlasProperties)) {
        String kafkaPrincipal = atlasProperties.getString("atlas.notification.kafka.service.principal");
        String kafkaKeyTab = atlasProperties.getString("atlas.notification.kafka.keytab.location");
        org.apache.hadoop.conf.Configuration hadoopConf = new org.apache.hadoop.conf.Configuration();
        SecurityUtil.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS, hadoopConf);
        try {
            String serverPrincipal = SecurityUtil.getServerPrincipal(kafkaPrincipal, (String) null);
            UserGroupInformation.setConfiguration(hadoopConf);
            UserGroupInformation.loginUserFromKeytab(serverPrincipal, kafkaKeyTab);
        } catch (IOException e) {
            LOG.warn("Could not login as {} from keytab file {}", kafkaPrincipal, kafkaKeyTab, e);
            return false;
        }
    }
    return true;
}
 
Example 3
Source File: HdfsRepository.java    From crate with Apache License 2.0 6 votes vote down vote up
private static String preparePrincipal(String originalPrincipal) {
    String finalPrincipal = originalPrincipal;
    // Don't worry about host name resolution if they don't have the _HOST pattern in the name.
    if (originalPrincipal.contains("_HOST")) {
        try {
            finalPrincipal = SecurityUtil.getServerPrincipal(originalPrincipal, getHostName());
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }

        if (originalPrincipal.equals(finalPrincipal) == false) {
            LOGGER.debug("Found service principal. Converted original principal name [{}] to server principal [{}]",
                originalPrincipal, finalPrincipal);
        }
    }
    return finalPrincipal;
}
 
Example 4
Source File: HAContext.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
private void setJaasConfiguration(Configuration conf) throws IOException {
  if ("false".equalsIgnoreCase(conf.get(
        ServerConfig.SERVER_HA_ZOOKEEPER_CLIENT_TICKET_CACHE,
        ServerConfig.SERVER_HA_ZOOKEEPER_CLIENT_TICKET_CACHE_DEFAULT))) {
    String keytabFile = conf.get(ServerConfig.SERVER_HA_ZOOKEEPER_CLIENT_KEYTAB);
    Preconditions.checkArgument(keytabFile.length() != 0, "Keytab File is not right.");
    String principal = conf.get(ServerConfig.SERVER_HA_ZOOKEEPER_CLIENT_PRINCIPAL);
    principal = SecurityUtil.getServerPrincipal(principal,
      conf.get(ServerConfig.RPC_ADDRESS, ServerConfig.RPC_ADDRESS_DEFAULT));
    Preconditions.checkArgument(principal.length() != 0, "Kerberos principal is not right.");

    // This is equivalent to writing a jaas.conf file and setting the system property, "java.security.auth.login.config", to
    // point to it (but this way we don't have to write a file, and it works better for the tests)
    JaasConfiguration.addEntryForKeytab(SENTRY_ZK_JAAS_NAME, principal, keytabFile);
  } else {
    // Create jaas conf for ticket cache
    JaasConfiguration.addEntryForTicketCache(SENTRY_ZK_JAAS_NAME);
  }
  javax.security.auth.login.Configuration.setConfiguration(JaasConfiguration.getInstance());
}
 
Example 5
Source File: Master.java    From incubator-tez with Apache License 2.0 5 votes vote down vote up
public static String getMasterPrincipal(Configuration conf)
    throws IOException {
  String masterHostname = getMasterAddress(conf).getHostName();
  // get kerberos principal for use as delegation token renewer
  return SecurityUtil.getServerPrincipal(getMasterUserName(conf),
      masterHostname);
}
 
Example 6
Source File: KerberosUtils.java    From imhotep with Apache License 2.0 5 votes vote down vote up
private static void with(String principal, String keytabPath) throws IOException {
    log.info("Setting keytab file of " + keytabPath + ", and principal to " + principal);
    checkArgument(!Strings.isNullOrEmpty(principal), "Unable to use a null/empty principal for keytab");
    checkArgument(!Strings.isNullOrEmpty(keytabPath), "Unable to use a null/empty keytab path");

    // do hostname substitution
    final String realPrincipal = SecurityUtil.getServerPrincipal(principal, (String) null);
    // actually login
    try {
        UserGroupInformation.loginUserFromKeytab(realPrincipal, keytabPath);
    } catch (IOException e) {
        checkKnownErrors(realPrincipal, e);
        throw e;
    }
}
 
Example 7
Source File: AuthFilter.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the configuration to be used by the authentication filter
 * to initialize the authentication handler.
 *
 * This filter retrieves all HBase configurations and passes those started
 * with REST_PREFIX to the authentication handler.  It is useful to support
 * plugging different authentication handlers.
*/
@Override
protected Properties getConfiguration(
    String configPrefix, FilterConfig filterConfig) throws ServletException {
  Properties props = super.getConfiguration(configPrefix, filterConfig);
  //setting the cookie path to root '/' so it is used for all resources.
  props.setProperty(AuthenticationFilter.COOKIE_PATH, "/");

  Configuration conf = null;
  // Dirty hack to get at the RESTServer's configuration. These should be pulled out
  // of the FilterConfig.
  if (RESTServer.conf != null) {
    conf = RESTServer.conf;
  } else {
    conf = HBaseConfiguration.create();
  }
  for (Map.Entry<String, String> entry : conf) {
    String name = entry.getKey();
    if (name.startsWith(REST_PREFIX)) {
      String value = entry.getValue();
      if(name.equals(REST_AUTHENTICATION_PRINCIPAL))  {
        try {
          String machineName = Strings.domainNamePointerToHostName(
            DNS.getDefaultHost(conf.get(REST_DNS_INTERFACE, "default"),
              conf.get(REST_DNS_NAMESERVER, "default")));
          value = SecurityUtil.getServerPrincipal(value, machineName);
        } catch (IOException ie) {
          throw new ServletException("Failed to retrieve server principal", ie);
        }
      }
      if (LOG.isTraceEnabled()) {
        LOG.trace("Setting property " + name + "=" + value);
      }
      name = name.substring(REST_PREFIX_LEN);
      props.setProperty(name, value);
    }
  }
  return props;
}
 
Example 8
Source File: ZKUtil.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Log in the current process using the given configuration keys for the
 * credential file and login principal.
 *
 * <p><strong>This is only applicable when running on secure hbase</strong>
 * On regular HBase (without security features), this will safely be ignored.
 * </p>
 *
 * @param conf The configuration data to use
 * @param keytabFileKey Property key used to configure the path to the credential file
 * @param userNameKey Property key used to configure the login principal
 * @param hostname Current hostname to use in any credentials
 * @param loginContextProperty property name to expose the entry name
 * @param loginContextName jaas entry name
 * @throws IOException underlying exception from SecurityUtil.login() call
 */
private static void login(Configuration conf, String keytabFileKey,
    String userNameKey, String hostname,
    String loginContextProperty, String loginContextName)
    throws IOException {
  if (!isSecureZooKeeper(conf)) {
    return;
  }

  // User has specified a jaas.conf, keep this one as the good one.
  // HBASE_OPTS="-Djava.security.auth.login.config=jaas.conf"
  if (System.getProperty("java.security.auth.login.config") != null) {
    return;
  }

  // No keytab specified, no auth
  String keytabFilename = conf.get(keytabFileKey);
  if (keytabFilename == null) {
    LOG.warn("no keytab specified for: {}", keytabFileKey);
    return;
  }

  String principalConfig = conf.get(userNameKey, System.getProperty("user.name"));
  String principalName = SecurityUtil.getServerPrincipal(principalConfig, hostname);

  // Initialize the "jaas.conf" for keyTab/principal,
  // If keyTab is not specified use the Ticket Cache.
  // and set the zookeeper login context name.
  JaasConfiguration jaasConf = new JaasConfiguration(loginContextName,
      principalName, keytabFilename);
  javax.security.auth.login.Configuration.setConfiguration(jaasConf);
  System.setProperty(loginContextProperty, loginContextName);
}
 
Example 9
Source File: YarnClientImpl.java    From big-c with Apache License 2.0 5 votes vote down vote up
private static String getTimelineDelegationTokenRenewer(Configuration conf)
    throws IOException, YarnException  {
  // Parse the RM daemon user if it exists in the config
  String rmPrincipal = conf.get(YarnConfiguration.RM_PRINCIPAL);
  String renewer = null;
  if (rmPrincipal != null && rmPrincipal.length() > 0) {
    String rmHost = conf.getSocketAddr(
        YarnConfiguration.RM_ADDRESS,
        YarnConfiguration.DEFAULT_RM_ADDRESS,
        YarnConfiguration.DEFAULT_RM_PORT).getHostName();
    renewer = SecurityUtil.getServerPrincipal(rmPrincipal, rmHost);
  }
  return renewer;
}
 
Example 10
Source File: YarnUtils.java    From twill with Apache License 2.0 5 votes vote down vote up
public static String getYarnTokenRenewer(Configuration config) throws IOException {
  String rmHost = getRMAddress(config).getHostName();
  String renewer = SecurityUtil.getServerPrincipal(config.get(YarnConfiguration.RM_PRINCIPAL), rmHost);

  if (renewer == null || renewer.length() == 0) {
    throw new IOException("No Kerberos principal for Yarn RM to use as renewer");
  }

  return renewer;
}
 
Example 11
Source File: YarnClientImpl.java    From hadoop with Apache License 2.0 5 votes vote down vote up
private static String getTimelineDelegationTokenRenewer(Configuration conf)
    throws IOException, YarnException  {
  // Parse the RM daemon user if it exists in the config
  String rmPrincipal = conf.get(YarnConfiguration.RM_PRINCIPAL);
  String renewer = null;
  if (rmPrincipal != null && rmPrincipal.length() > 0) {
    String rmHost = conf.getSocketAddr(
        YarnConfiguration.RM_ADDRESS,
        YarnConfiguration.DEFAULT_RM_ADDRESS,
        YarnConfiguration.DEFAULT_RM_PORT).getHostName();
    renewer = SecurityUtil.getServerPrincipal(rmPrincipal, rmHost);
  }
  return renewer;
}
 
Example 12
Source File: OlapServerSubmitter.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
private String prepareCommands(String exec, String parameters, String sparkYarnQueue) throws IOException {
    StringBuilder result = new StringBuilder();
    result.append(exec);
    for (Object sysPropertyKey : System.getProperties().keySet()) {
        String spsPropertyName = (String) sysPropertyKey;
        if (spsPropertyName.contains("spark.yarn.queue"))
            continue; // we'll set the appropriate yarn queue later
        if (spsPropertyName.startsWith("splice.spark") || spsPropertyName.startsWith("spark")) {
            if (spsPropertyName.equals(KEYTAB_KEY)) {
                LOG.info(KEYTAB_KEY + " is set, substituting it for " + amKeytabFileName);
                result.append(' ').append("-D"+spsPropertyName+"="+amKeytabFileName);
                continue;
            }
            String sysPropertyValue = System.getProperty(spsPropertyName).replace('\n', ' ');
            if (sysPropertyValue != null) {
                result.append(' ').append("-D"+spsPropertyName+"=\\\""+sysPropertyValue+"\\\"");
            }
        }
    }
    result.append(' ').append("-Dspark.yarn.queue=\\\""+sparkYarnQueue+"\\\"");
    result.append(' ').append("-Dsplice.spark.app.name=\\\"SpliceMachine-"+queueName+"\\\"");
    // If user does not specify a kerberos keytab or principal, use HBase master's.
    if (UserGroupInformation.isSecurityEnabled()) {
        Configuration configuration = HConfiguration.unwrapDelegate();
        String principal = System.getProperty(PRINCIPAL_KEY);
        String keytab = System.getProperty(KEYTAB_KEY);
        if (principal == null || keytab == null) {
            principal = configuration.get(HBASE_MASTER_PRINCIPAL_KEY);
            String hostname = NetworkUtils.getHostname(HConfiguration.getConfiguration());
            principal = SecurityUtil.getServerPrincipal(principal, hostname);
            SpliceLogUtils.info(LOG, "User did not specify principal or keytab, use default principal=%s, keytab=%s", principal, amKeytabFileName);
            result.append(' ').append("-D"+PRINCIPAL_KEY+"="+principal);
            result.append(' ').append("-D"+KEYTAB_KEY+"="+amKeytabFileName);
        }
    }
    String extraOptions = System.getProperty("splice.olapServer.extraJavaOptions");
    if (extraOptions != null) {
        for (String option : extraOptions.split("\\s+")) {
            result.append(' ').append(option);
        }
    }
    result.append(' ').append(parameters);
    String command = result.toString();
    LOG.info("OlapServer command: " + command);
    return command;
}
 
Example 13
Source File: ServiceAuthorizationManager.java    From big-c with Apache License 2.0 4 votes vote down vote up
/**
 * Authorize the user to access the protocol being used.
 * 
 * @param user user accessing the service 
 * @param protocol service being accessed
 * @param conf configuration to use
 * @param addr InetAddress of the client
 * @throws AuthorizationException on authorization failure
 */
public void authorize(UserGroupInformation user, 
                             Class<?> protocol,
                             Configuration conf,
                             InetAddress addr
                             ) throws AuthorizationException {
  AccessControlList[] acls = protocolToAcls.get(protocol);
  MachineList[] hosts = protocolToMachineLists.get(protocol);
  if (acls == null || hosts == null) {
    throw new AuthorizationException("Protocol " + protocol + 
                                     " is not known.");
  }
  
  // get client principal key to verify (if available)
  KerberosInfo krbInfo = SecurityUtil.getKerberosInfo(protocol, conf);
  String clientPrincipal = null; 
  if (krbInfo != null) {
    String clientKey = krbInfo.clientPrincipal();
    if (clientKey != null && !clientKey.isEmpty()) {
      try {
        clientPrincipal = SecurityUtil.getServerPrincipal(
            conf.get(clientKey), addr);
      } catch (IOException e) {
        throw (AuthorizationException) new AuthorizationException(
            "Can't figure out Kerberos principal name for connection from "
                + addr + " for user=" + user + " protocol=" + protocol)
            .initCause(e);
      }
    }
  }
  if((clientPrincipal != null && !clientPrincipal.equals(user.getUserName())) || 
     acls.length != 2  || !acls[0].isUserAllowed(user) || acls[1].isUserAllowed(user)) {
    AUDITLOG.warn(AUTHZ_FAILED_FOR + user + " for protocol=" + protocol
        + ", expected client Kerberos principal is " + clientPrincipal);
    throw new AuthorizationException("User " + user + 
        " is not authorized for protocol " + protocol + 
        ", expected client Kerberos principal is " + clientPrincipal);
  }
  if (addr != null) {
    String hostAddress = addr.getHostAddress();
    if (hosts.length != 2 || !hosts[0].includes(hostAddress) ||
        hosts[1].includes(hostAddress)) {
      AUDITLOG.warn(AUTHZ_FAILED_FOR + " for protocol=" + protocol
          + " from host = " +  hostAddress);
      throw new AuthorizationException("Host " + hostAddress +
          " is not authorized for protocol " + protocol) ;
    }
  }
  AUDITLOG.info(AUTHZ_SUCCESSFUL_FOR + user + " for protocol="+protocol);
}
 
Example 14
Source File: SqoopAuthenticationFilter.java    From sqoop-on-spark with Apache License 2.0 4 votes vote down vote up
@Override
protected Properties getConfiguration(String configPrefix,
                                      FilterConfig filterConfig) throws ServletException {
  Properties properties = new Properties();
  MapContext mapContext = SqoopConfiguration.getInstance().getContext();
  String type = mapContext.getString(
      SecurityConstants.AUTHENTICATION_TYPE,
      SecurityConstants.TYPE.SIMPLE.name()).trim();

  if (type.equalsIgnoreCase(SecurityConstants.TYPE.KERBEROS.name())) {
    properties.setProperty(AUTH_TYPE, KerberosDelegationTokenAuthenticationHandler.class.getName());

    String keytab = mapContext.getString(
            SecurityConstants.AUTHENTICATION_KERBEROS_HTTP_KEYTAB).trim();
    if (keytab.length() == 0) {
      throw new SqoopException(SecurityError.AUTH_0005,
              SecurityConstants.AUTHENTICATION_KERBEROS_HTTP_KEYTAB);
    }

    String principal = mapContext.getString(
            SecurityConstants.AUTHENTICATION_KERBEROS_HTTP_PRINCIPAL).trim();
    if (principal.length() == 0) {
      throw new SqoopException(SecurityError.AUTH_0006,
              SecurityConstants.AUTHENTICATION_KERBEROS_HTTP_PRINCIPAL);
    }

    String hostPrincipal = "";
    try {
      hostPrincipal = SecurityUtil.getServerPrincipal(principal, "0.0.0.0");
    } catch (IOException e) {
      throw new SqoopException(SecurityError.AUTH_0006,
              SecurityConstants.AUTHENTICATION_KERBEROS_HTTP_PRINCIPAL);
    }

    properties.setProperty(KerberosAuthenticationHandler.PRINCIPAL, hostPrincipal);
    properties.setProperty(KerberosAuthenticationHandler.KEYTAB, keytab);
  } else if (type.equalsIgnoreCase(SecurityConstants.TYPE.SIMPLE.name())) {
    properties.setProperty(AUTH_TYPE, PseudoDelegationTokenAuthenticationHandler.class.getName());
    properties.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED,
        mapContext.getString(SecurityConstants.AUTHENTICATION_ANONYMOUS, "true").trim());
  } else {
    throw new SqoopException(SecurityError.AUTH_0004, type);
  }

  properties.setProperty(DelegationTokenAuthenticationHandler.TOKEN_KIND,
          SecurityConstants.TOKEN_KIND);

  return properties;
}
 
Example 15
Source File: SentryPolicyServiceClientDefaultImpl.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
public SentryPolicyServiceClientDefaultImpl(Configuration conf) throws IOException {
  this.conf = conf;
  Preconditions.checkNotNull(this.conf, "Configuration object cannot be null");
  this.serverAddress = NetUtils.createSocketAddr(Preconditions.checkNotNull(
                         conf.get(ClientConfig.SERVER_RPC_ADDRESS), "Config key "
                         + ClientConfig.SERVER_RPC_ADDRESS + " is required"), conf.getInt(
                         ClientConfig.SERVER_RPC_PORT, ClientConfig.SERVER_RPC_PORT_DEFAULT));
  this.connectionTimeout = conf.getInt(ClientConfig.SERVER_RPC_CONN_TIMEOUT,
                                       ClientConfig.SERVER_RPC_CONN_TIMEOUT_DEFAULT);
  kerberos = ServerConfig.SECURITY_MODE_KERBEROS.equalsIgnoreCase(
      conf.get(ServerConfig.SECURITY_MODE, ServerConfig.SECURITY_MODE_KERBEROS).trim());
  transport = new TSocket(serverAddress.getHostName(),
      serverAddress.getPort(), connectionTimeout);
  if (kerberos) {
    String serverPrincipal = Preconditions.checkNotNull(conf.get(ServerConfig.PRINCIPAL), ServerConfig.PRINCIPAL + " is required");

    // Resolve server host in the same way as we are doing on server side
    serverPrincipal = SecurityUtil.getServerPrincipal(serverPrincipal, serverAddress.getAddress());
    LOGGER.debug("Using server kerberos principal: " + serverPrincipal);

    serverPrincipalParts = SaslRpcServer.splitKerberosName(serverPrincipal);
    Preconditions.checkArgument(serverPrincipalParts.length == 3,
         "Kerberos principal should have 3 parts: " + serverPrincipal);
    boolean wrapUgi = "true".equalsIgnoreCase(conf
        .get(ServerConfig.SECURITY_USE_UGI_TRANSPORT, "true"));
    transport = new UgiSaslClientTransport(AuthMethod.KERBEROS.getMechanismName(),
        null, serverPrincipalParts[0], serverPrincipalParts[1],
        ClientConfig.SASL_PROPERTIES, null, transport, wrapUgi);
  } else {
    serverPrincipalParts = null;
  }
  try {
    transport.open();
  } catch (TTransportException e) {
    throw new IOException("Transport exception while opening transport: " + e.getMessage(), e);
  }
  LOGGER.debug("Successfully opened transport: " + transport + " to " + serverAddress);
  long maxMessageSize = conf.getLong(ServiceConstants.ClientConfig.SENTRY_POLICY_CLIENT_THRIFT_MAX_MESSAGE_SIZE,
      ServiceConstants.ClientConfig.SENTRY_POLICY_CLIENT_THRIFT_MAX_MESSAGE_SIZE_DEFAULT);
  TMultiplexedProtocol protocol = new TMultiplexedProtocol(
      new TBinaryProtocol(transport, maxMessageSize, maxMessageSize, true, true),
      SentryPolicyStoreProcessor.SENTRY_POLICY_SERVICE_NAME);
  client = new SentryPolicyService.Client(protocol);
  LOGGER.debug("Successfully created client");
}
 
Example 16
Source File: SentryGenericServiceClientDefaultImpl.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
public SentryGenericServiceClientDefaultImpl(Configuration conf) throws IOException {
  // copy the configuration because we may make modifications to it.
  this.conf = new Configuration(conf);
  Preconditions.checkNotNull(this.conf, "Configuration object cannot be null");
  this.serverAddress = NetUtils.createSocketAddr(Preconditions.checkNotNull(
                         conf.get(ClientConfig.SERVER_RPC_ADDRESS), "Config key "
                         + ClientConfig.SERVER_RPC_ADDRESS + " is required"), conf.getInt(
                         ClientConfig.SERVER_RPC_PORT, ClientConfig.SERVER_RPC_PORT_DEFAULT));
  this.connectionTimeout = conf.getInt(ClientConfig.SERVER_RPC_CONN_TIMEOUT,
                                       ClientConfig.SERVER_RPC_CONN_TIMEOUT_DEFAULT);
  kerberos = ServerConfig.SECURITY_MODE_KERBEROS.equalsIgnoreCase(
      conf.get(ServerConfig.SECURITY_MODE, ServerConfig.SECURITY_MODE_KERBEROS).trim());
  transport = new TSocket(serverAddress.getHostName(),
      serverAddress.getPort(), connectionTimeout);
  if (kerberos) {
    String serverPrincipal = Preconditions.checkNotNull(conf.get(ServerConfig.PRINCIPAL), ServerConfig.PRINCIPAL + " is required");
    // since the client uses hadoop-auth, we need to set kerberos in
    // hadoop-auth if we plan to use kerberos
    conf.set(HADOOP_SECURITY_AUTHENTICATION, ServerConfig.SECURITY_MODE_KERBEROS);

    // Resolve server host in the same way as we are doing on server side
    serverPrincipal = SecurityUtil.getServerPrincipal(serverPrincipal, serverAddress.getAddress());
    LOGGER.debug("Using server kerberos principal: " + serverPrincipal);

    serverPrincipalParts = SaslRpcServer.splitKerberosName(serverPrincipal);
    Preconditions.checkArgument(serverPrincipalParts.length == 3,
         "Kerberos principal should have 3 parts: " + serverPrincipal);
    boolean wrapUgi = "true".equalsIgnoreCase(conf
        .get(ServerConfig.SECURITY_USE_UGI_TRANSPORT, "true"));
    transport = new UgiSaslClientTransport(AuthMethod.KERBEROS.getMechanismName(),
        null, serverPrincipalParts[0], serverPrincipalParts[1],
        ClientConfig.SASL_PROPERTIES, null, transport, wrapUgi, conf);
  } else {
    serverPrincipalParts = null;
  }
  try {
    transport.open();
  } catch (TTransportException e) {
    throw new IOException("Transport exception while opening transport: " + e.getMessage(), e);
  }
  LOGGER.debug("Successfully opened transport: " + transport + " to " + serverAddress);
  long maxMessageSize = conf.getLong(ServiceConstants.ClientConfig.SENTRY_POLICY_CLIENT_THRIFT_MAX_MESSAGE_SIZE,
      ServiceConstants.ClientConfig.SENTRY_POLICY_CLIENT_THRIFT_MAX_MESSAGE_SIZE_DEFAULT);
  TMultiplexedProtocol protocol = new TMultiplexedProtocol(
      new TBinaryProtocol(transport, maxMessageSize, maxMessageSize, true, true),
      SentryGenericPolicyProcessor.SENTRY_GENERIC_SERVICE_NAME);
  client = new SentryGenericPolicyService.Client(protocol);
  LOGGER.debug("Successfully created client");
}
 
Example 17
Source File: ServiceAuthorizationManager.java    From hadoop with Apache License 2.0 4 votes vote down vote up
/**
 * Authorize the user to access the protocol being used.
 * 
 * @param user user accessing the service 
 * @param protocol service being accessed
 * @param conf configuration to use
 * @param addr InetAddress of the client
 * @throws AuthorizationException on authorization failure
 */
public void authorize(UserGroupInformation user, 
                             Class<?> protocol,
                             Configuration conf,
                             InetAddress addr
                             ) throws AuthorizationException {
  AccessControlList[] acls = protocolToAcls.get(protocol);
  MachineList[] hosts = protocolToMachineLists.get(protocol);
  if (acls == null || hosts == null) {
    throw new AuthorizationException("Protocol " + protocol + 
                                     " is not known.");
  }
  
  // get client principal key to verify (if available)
  KerberosInfo krbInfo = SecurityUtil.getKerberosInfo(protocol, conf);
  String clientPrincipal = null; 
  if (krbInfo != null) {
    String clientKey = krbInfo.clientPrincipal();
    if (clientKey != null && !clientKey.isEmpty()) {
      try {
        clientPrincipal = SecurityUtil.getServerPrincipal(
            conf.get(clientKey), addr);
      } catch (IOException e) {
        throw (AuthorizationException) new AuthorizationException(
            "Can't figure out Kerberos principal name for connection from "
                + addr + " for user=" + user + " protocol=" + protocol)
            .initCause(e);
      }
    }
  }
  if((clientPrincipal != null && !clientPrincipal.equals(user.getUserName())) || 
     acls.length != 2  || !acls[0].isUserAllowed(user) || acls[1].isUserAllowed(user)) {
    AUDITLOG.warn(AUTHZ_FAILED_FOR + user + " for protocol=" + protocol
        + ", expected client Kerberos principal is " + clientPrincipal);
    throw new AuthorizationException("User " + user + 
        " is not authorized for protocol " + protocol + 
        ", expected client Kerberos principal is " + clientPrincipal);
  }
  if (addr != null) {
    String hostAddress = addr.getHostAddress();
    if (hosts.length != 2 || !hosts[0].includes(hostAddress) ||
        hosts[1].includes(hostAddress)) {
      AUDITLOG.warn(AUTHZ_FAILED_FOR + " for protocol=" + protocol
          + " from host = " +  hostAddress);
      throw new AuthorizationException("Host " + hostAddress +
          " is not authorized for protocol " + protocol) ;
    }
  }
  AUDITLOG.info(AUTHZ_SUCCESSFUL_FOR + user + " for protocol="+protocol);
}
 
Example 18
Source File: SentryService.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
public SentryService(Configuration conf) {
  this.conf = conf;
  int port = conf
      .getInt(ServerConfig.RPC_PORT, ServerConfig.RPC_PORT_DEFAULT);
  if (port == 0) {
    port = findFreePort();
    conf.setInt(ServerConfig.RPC_PORT, port);
  }
  this.address = NetUtils.createSocketAddr(
      conf.get(ServerConfig.RPC_ADDRESS, ServerConfig.RPC_ADDRESS_DEFAULT),
      port);
  LOGGER.info("Configured on address " + address);
  kerberos = ServerConfig.SECURITY_MODE_KERBEROS.equalsIgnoreCase(
      conf.get(ServerConfig.SECURITY_MODE, ServerConfig.SECURITY_MODE_KERBEROS).trim());
  maxThreads = conf.getInt(ServerConfig.RPC_MAX_THREADS,
      ServerConfig.RPC_MAX_THREADS_DEFAULT);
  minThreads = conf.getInt(ServerConfig.RPC_MIN_THREADS,
      ServerConfig.RPC_MIN_THREADS_DEFAULT);
  maxMessageSize = conf.getLong(ServerConfig.SENTRY_POLICY_SERVER_THRIFT_MAX_MESSAGE_SIZE,
      ServerConfig.SENTRY_POLICY_SERVER_THRIFT_MAX_MESSAGE_SIZE_DEFAULT);
  if (kerberos) {
    // Use Hadoop libraries to translate the _HOST placeholder with actual hostname
    try {
      String rawPrincipal = Preconditions.checkNotNull(conf.get(ServerConfig.PRINCIPAL), ServerConfig.PRINCIPAL + " is required");
      principal = SecurityUtil.getServerPrincipal(rawPrincipal, address.getAddress());
    } catch(IOException io) {
      throw new RuntimeException("Can't translate kerberos principal'", io);
    }
    LOGGER.info("Using kerberos principal: " + principal);

    principalParts = SaslRpcServer.splitKerberosName(principal);
    Preconditions.checkArgument(principalParts.length == 3,
        "Kerberos principal should have 3 parts: " + principal);
    keytab = Preconditions.checkNotNull(conf.get(ServerConfig.KEY_TAB),
        ServerConfig.KEY_TAB + " is required");
    File keytabFile = new File(keytab);
    Preconditions.checkState(keytabFile.isFile() && keytabFile.canRead(),
        "Keytab " + keytab + " does not exist or is not readable.");
  } else {
    principal = null;
    principalParts = null;
    keytab = null;
  }
  serviceExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
    private int count = 0;

    @Override
    public Thread newThread(Runnable r) {
      return new Thread(r, SentryService.class.getSimpleName() + "-"
          + (count++));
    }
  });
  webServerPort = conf.getInt(ServerConfig.SENTRY_WEB_PORT, ServerConfig.SENTRY_WEB_PORT_DEFAULT);
  status = Status.NOT_STARTED;
}
 
Example 19
Source File: LoginProcessor.java    From incubator-atlas with Apache License 2.0 2 votes vote down vote up
/**
 * Return a server (service) principal.  The token "_HOST" in the principal will be replaced with the local host
 * name (e.g. dgi/_HOST will be changed to dgi/localHostName)
 * @param principal the input principal containing an option "_HOST" token
 * @return the service principal.
 * @throws IOException
 */
private String getServerPrincipal(String principal, String host) throws IOException {
    return SecurityUtil.getServerPrincipal(principal, host);
}
 
Example 20
Source File: LoginProcessor.java    From atlas with Apache License 2.0 2 votes vote down vote up
/**
 * Return a server (service) principal.  The token "_HOST" in the principal will be replaced with the local host
 * name (e.g. dgi/_HOST will be changed to dgi/localHostName)
 * @param principal the input principal containing an option "_HOST" token
 * @return the service principal.
 * @throws IOException
 */
private String getServerPrincipal(String principal, String host) throws IOException {
    return SecurityUtil.getServerPrincipal(principal, host);
}