List of usage examples for org.apache.hadoop.security.authentication.util KerberosName KerberosName
public KerberosName(String name)
From source file:co.cask.cdap.data2.datafabric.dataset.DatasetServiceClient.java
License:Apache License
DatasetServiceClient(final DiscoveryServiceClient discoveryClient, NamespaceId namespaceId, CConfiguration cConf, AuthenticationContext authenticationContext) { this.remoteClient = new RemoteClient(discoveryClient, Constants.Service.DATASET_MANAGER, new DefaultHttpRequestConfig(false), String.format("%s/namespaces/%s/data", Constants.Gateway.API_VERSION_3, namespaceId.getNamespace())); this.namespaceId = namespaceId; this.securityEnabled = cConf.getBoolean(Constants.Security.ENABLED); this.kerberosEnabled = SecurityUtil.isKerberosEnabled(cConf); this.authorizationEnabled = cConf.getBoolean(Constants.Security.Authorization.ENABLED); this.authenticationContext = authenticationContext; String masterPrincipal = cConf.get(Constants.Security.CFG_CDAP_MASTER_KRB_PRINCIPAL); try {// ww w. j a v a 2s . c o m if (securityEnabled && kerberosEnabled) { this.masterShortUserName = new KerberosName(masterPrincipal).getShortName(); } else { this.masterShortUserName = null; } } catch (IOException e) { throw Throwables.propagate(e); } }
From source file:co.cask.cdap.internal.app.namespace.DefaultNamespaceAdmin.java
License:Apache License
@Inject DefaultNamespaceAdmin(NamespaceStore nsStore, DatasetFramework dsFramework, Provider<NamespaceResourceDeleter> resourceDeleter, Provider<ProgramRuntimeService> runtimeService, Provider<StorageProviderNamespaceAdmin> storageProviderNamespaceAdmin, PrivilegesManager privilegesManager, CConfiguration cConf, Impersonator impersonator, AuthorizationEnforcer authorizationEnforcer, AuthenticationContext authenticationContext) { this.resourceDeleter = resourceDeleter; this.nsStore = nsStore; this.dsFramework = dsFramework; this.runtimeService = runtimeService; this.privilegesManager = privilegesManager; this.authenticationContext = authenticationContext; this.authorizationEnforcer = authorizationEnforcer; this.instanceId = createInstanceId(cConf); this.storageProviderNamespaceAdmin = storageProviderNamespaceAdmin; this.impersonator = impersonator; this.cConf = cConf; this.namespaceMetaCache = CacheBuilder.newBuilder().build(new CacheLoader<NamespaceId, NamespaceMeta>() { @Override//from ww w . ja v a2 s. c o m public NamespaceMeta load(NamespaceId namespaceId) throws Exception { return fetchNamespaceMeta(namespaceId); } }); String masterPrincipal = cConf.get(Constants.Security.CFG_CDAP_MASTER_KRB_PRINCIPAL); try { if (SecurityUtil.isKerberosEnabled(cConf)) { this.masterShortUserName = new KerberosName(masterPrincipal).getShortName(); } else { this.masterShortUserName = null; } } catch (IOException e) { throw Throwables.propagate(e); } }
From source file:co.cask.cdap.internal.app.namespace.DefaultNamespaceAdmin.java
License:Apache License
/** * Creates a new namespace//from w ww. ja v a 2s. com * * @param metadata the {@link NamespaceMeta} for the new namespace to be created * @throws NamespaceAlreadyExistsException if the specified namespace already exists */ @Override @AuthEnforce(entities = "instanceId", enforceOn = InstanceId.class, actions = Action.ADMIN) public synchronized void create(final NamespaceMeta metadata) throws Exception { // TODO: CDAP-1427 - This should be transactional, but we don't support transactions on files yet Preconditions.checkArgument(metadata != null, "Namespace metadata should not be null."); NamespaceId namespace = metadata.getNamespaceId(); if (exists(namespace)) { throw new NamespaceAlreadyExistsException(namespace); } // If this namespace has custom mapping then validate the given custom mapping if (hasCustomMapping(metadata)) { validateCustomMapping(metadata); } // check that the user has configured either both of none of the following configuration: principal and keytab URI boolean hasValidKerberosConf = false; if (metadata.getConfig() != null) { String configuredPrincipal = metadata.getConfig().getPrincipal(); String configuredKeytabURI = metadata.getConfig().getKeytabURI(); if ((!Strings.isNullOrEmpty(configuredPrincipal) && Strings.isNullOrEmpty(configuredKeytabURI)) || (Strings.isNullOrEmpty(configuredPrincipal) && !Strings.isNullOrEmpty(configuredKeytabURI))) { throw new BadRequestException(String.format( "Either neither or both of the following two configurations must be configured. " + "Configured principal: %s, Configured keytabURI: %s", configuredPrincipal, configuredKeytabURI)); } hasValidKerberosConf = true; } // check that if explore as principal is explicitly set to false then user has kerberos configuration if (!metadata.getConfig().isExploreAsPrincipal() && !hasValidKerberosConf) { throw new BadRequestException( String.format("No kerberos principal or keytab-uri was provided while '%s' was set to true.", NamespaceConfig.EXPLORE_AS_PRINCIPAL)); } // Namespace can be created. Grant all the permissions to the user. Principal principal = authenticationContext.getPrincipal(); privilegesManager.grant(namespace, principal, EnumSet.allOf(Action.class)); // Also grant the user who will execute programs in this namespace all privileges on the namespace String executionUserName; if (SecurityUtil.isKerberosEnabled(cConf) && !NamespaceId.SYSTEM.equals(namespace)) { String namespacePrincipal = metadata.getConfig().getPrincipal(); if (Strings.isNullOrEmpty(namespacePrincipal)) { executionUserName = SecurityUtil.getMasterPrincipal(cConf); } else { executionUserName = new KerberosName(namespacePrincipal).getShortName(); } } else { executionUserName = UserGroupInformation.getCurrentUser().getShortUserName(); } Principal executionUser = new Principal(executionUserName, Principal.PrincipalType.USER); privilegesManager.grant(namespace, executionUser, EnumSet.allOf(Action.class)); // store the meta first in the namespace store because namespacedLocationFactory needs to look up location // mapping from namespace config nsStore.create(metadata); UserGroupInformation ugi; if (NamespaceId.DEFAULT.equals(namespace)) { ugi = UserGroupInformation.getCurrentUser(); } else { ugi = impersonator.getUGI(namespace); } try { ImpersonationUtils.doAs(ugi, new Callable<Void>() { @Override public Void call() throws Exception { storageProviderNamespaceAdmin.get().create(metadata); return null; } }); } catch (Throwable t) { // failed to create namespace in underlying storage so delete the namespace meta stored in the store earlier deleteNamespaceMeta(metadata.getNamespaceId()); privilegesManager.revoke(namespace); throw new NamespaceCannotBeCreatedException(namespace, t); } LOG.info("Namespace {} created with meta {}", metadata.getNamespaceId(), metadata); }
From source file:co.cask.cdap.internal.app.runtime.schedule.ScheduleTaskRunner.java
License:Apache License
/** * Executes a program without blocking until its completion. * * @return a {@link ListenableFuture} object that completes when the program completes *//*ww w .jav a 2 s .c o m*/ private ListenableFuture<?> execute(final ProgramId id, Map<String, String> sysArgs, Map<String, String> userArgs) throws Exception { ProgramRuntimeService.RuntimeInfo runtimeInfo; String originalUserId = SecurityRequestContext.getUserId(); try { // if the program has a namespace user configured then set that user in the security request context. // See: CDAP-7396 String nsPrincipal = namespaceQueryAdmin.get(id.getNamespaceId()).getConfig().getPrincipal(); if (nsPrincipal != null && SecurityUtil.isKerberosEnabled(cConf)) { SecurityRequestContext.setUserId(new KerberosName(nsPrincipal).getServiceName()); } runtimeInfo = lifecycleService.start(id, sysArgs, userArgs, false); } catch (ProgramNotFoundException | ApplicationNotFoundException e) { throw new TaskExecutionException( String.format(UserMessages.getMessage(UserErrors.PROGRAM_NOT_FOUND), id), e, false); } finally { SecurityRequestContext.setUserId(originalUserId); } final ProgramController controller = runtimeInfo.getController(); final CountDownLatch latch = new CountDownLatch(1); controller.addListener(new AbstractListener() { @Override public void init(ProgramController.State state, @Nullable Throwable cause) { if (state == ProgramController.State.COMPLETED) { completed(); } if (state == ProgramController.State.ERROR) { error(controller.getFailureCause()); } } @Override public void killed() { latch.countDown(); } @Override public void completed() { latch.countDown(); } @Override public void error(Throwable cause) { latch.countDown(); } }, Threads.SAME_THREAD_EXECUTOR); return executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { latch.await(); return null; } }); }
From source file:co.cask.cdap.security.impersonation.DefaultImpersonator.java
License:Apache License
private UserGroupInformation getUGI(ImpersonationInfo impersonationInfo) throws IOException { // no need to get a UGI if the current UGI is the one we're requesting; simply return it String configuredPrincipalShortName = new KerberosName(impersonationInfo.getPrincipal()).getShortName(); if (UserGroupInformation.getCurrentUser().getShortUserName().equals(configuredPrincipalShortName)) { return UserGroupInformation.getCurrentUser(); }/*from www. j av a 2 s . com*/ return ugiProvider.getConfiguredUGI(impersonationInfo); }
From source file:io.druid.security.kerberos.DruidKerberosAuthenticationHandler.java
License:Apache License
@Override public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException { AuthenticationToken token = null;/*from ww w .j a v a 2 s . co m*/ String authorization = request .getHeader(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.AUTHORIZATION); if (authorization == null || !authorization .startsWith(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE)) { return null; } else { authorization = authorization.substring( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE.length()) .trim(); final Base64 base64 = new Base64(0); final byte[] clientToken = base64.decode(authorization); final String serverName = request.getServerName(); try { token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() { @Override public AuthenticationToken run() throws Exception { AuthenticationToken token = null; GSSContext gssContext = null; GSSCredential gssCreds = null; try { gssCreds = gssManager.createCredential( gssManager.createName(KerberosUtil.getServicePrincipal("HTTP", serverName), KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL")), GSSCredential.INDEFINITE_LIFETIME, new Oid[] { KerberosUtil.getOidInstance("GSS_SPNEGO_MECH_OID"), KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID") }, GSSCredential.ACCEPT_ONLY); gssContext = gssManager.createContext(gssCreds); byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length); if (serverToken != null && serverToken.length > 0) { String authenticate = base64.encodeToString(serverToken); response.setHeader( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE, org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE + " " + authenticate); } if (!gssContext.isEstablished()) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); log.trace("SPNEGO in progress"); } else { String clientPrincipal = gssContext.getSrcName().toString(); KerberosName kerberosName = new KerberosName(clientPrincipal); String userName = kerberosName.getShortName(); token = new AuthenticationToken(userName, clientPrincipal, getType()); response.setStatus(HttpServletResponse.SC_OK); log.trace("SPNEGO completed for principal [%s]", clientPrincipal); } } finally { if (gssContext != null) { gssContext.dispose(); } if (gssCreds != null) { gssCreds.dispose(); } } return token; } }); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } else { throw new AuthenticationException(ex.getException()); } } } return token; }
From source file:org.apache.accumulo.core.client.impl.ClientConfConverter.java
License:Apache License
@SuppressWarnings("deprecation") public static org.apache.accumulo.core.client.ClientConfiguration toClientConf(AccumuloConfiguration conf) { org.apache.accumulo.core.client.ClientConfiguration clientConf = org.apache.accumulo.core.client.ClientConfiguration .create();/*w w w . j a v a 2 s . co m*/ // Servers will only have the full principal in their configuration -- parse the // primary and realm from it. final String serverPrincipal = conf.get(Property.GENERAL_KERBEROS_PRINCIPAL); final KerberosName krbName; if (serverPrincipal != null && !serverPrincipal.isEmpty()) { krbName = new KerberosName(serverPrincipal); clientConf.setProperty( org.apache.accumulo.core.client.ClientConfiguration.ClientProperty.KERBEROS_SERVER_PRIMARY, krbName.getServiceName()); } HashSet<String> clientKeys = new HashSet<>(); for (org.apache.accumulo.core.client.ClientConfiguration.ClientProperty prop : org.apache.accumulo.core.client.ClientConfiguration.ClientProperty .values()) { clientKeys.add(prop.getKey()); } String key; for (Map.Entry<String, String> entry : conf) { key = entry.getKey(); if (clientKeys.contains(key)) { clientConf.setProperty(key, entry.getValue()); } } return clientConf; }
From source file:org.apache.accumulo.core.rpc.SaslConnectionParams.java
License:Apache License
protected static Map<String, String> getProperties(AccumuloConfiguration conf) { final Map<String, String> clientProperties = new HashMap<>(); // Servers will only have the full principal in their configuration -- parse the // primary and realm from it. final String serverPrincipal = conf.get(Property.GENERAL_KERBEROS_PRINCIPAL); final KerberosName krbName; try {// w w w . j a v a2 s . c o m krbName = new KerberosName(serverPrincipal); clientProperties.put(ClientProperty.KERBEROS_SERVER_PRIMARY.getKey(), krbName.getServiceName()); } catch (Exception e) { // bad value or empty, assume we're not using kerberos } HashSet<String> clientKeys = new HashSet<>(); for (ClientProperty prop : ClientProperty.values()) { clientKeys.add(prop.getKey()); } String key; for (Entry<String, String> entry : conf) { key = entry.getKey(); if (clientKeys.contains(key)) { clientProperties.put(key, entry.getValue()); } } return clientProperties; }
From source file:org.apache.ambari.server.view.ViewContextImpl.java
License:Apache License
@Override public String getUsername() { String shortName = getLoggedinUser(); try {//from w ww . ja v a2 s . c om String authToLocalRules = getAuthToLocalRules(); //Getting ambari server realm. Ideally this should come from user String defaultRealm = KerberosUtil.getDefaultRealm(); if (Strings.isNotEmpty(authToLocalRules) && Strings.isNotEmpty(defaultRealm)) { synchronized (KerberosName.class) { KerberosName.setRules(authToLocalRules); shortName = new KerberosName(shortName + "@" + defaultRealm).getShortName(); } } } catch (InvocationTargetException e) { LOG.debug("Failed to get default realm", e); } catch (Exception e) { LOG.warn("Failed to apply auth_to_local rules. " + e.getMessage()); LOG.debug("Failed to apply auth_to_local rules", e); } return shortName; }
From source file:org.apache.druid.security.kerberos.DruidKerberosAuthenticationHandler.java
License:Apache License
@Override public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException { AuthenticationToken token;//from w w w. j a v a2 s . co m String authorization = request .getHeader(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.AUTHORIZATION); if (authorization == null || !authorization .startsWith(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE)) { return null; } else { authorization = authorization.substring( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE.length()) .trim(); final byte[] clientToken = StringUtils.decodeBase64String(authorization); final String serverName = request.getServerName(); try { token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() { @Override public AuthenticationToken run() throws Exception { AuthenticationToken token = null; GSSContext gssContext = null; GSSCredential gssCreds = null; try { gssCreds = gssManager.createCredential( gssManager.createName(KerberosUtil.getServicePrincipal("HTTP", serverName), KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL")), GSSCredential.INDEFINITE_LIFETIME, new Oid[] { KerberosUtil.getOidInstance("GSS_SPNEGO_MECH_OID"), KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID") }, GSSCredential.ACCEPT_ONLY); gssContext = gssManager.createContext(gssCreds); byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length); if (serverToken != null && serverToken.length > 0) { String authenticate = StringUtils.encodeBase64String(serverToken); response.setHeader( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE, org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE + " " + authenticate); } if (!gssContext.isEstablished()) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); log.trace("SPNEGO in progress"); } else { String clientPrincipal = gssContext.getSrcName().toString(); KerberosName kerberosName = new KerberosName(clientPrincipal); String userName = kerberosName.getShortName(); token = new AuthenticationToken(userName, clientPrincipal, getType()); response.setStatus(HttpServletResponse.SC_OK); log.trace("SPNEGO completed for principal [%s]", clientPrincipal); } } finally { if (gssContext != null) { gssContext.dispose(); } if (gssCreds != null) { gssCreds.dispose(); } } return token; } }); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } else { throw new AuthenticationException(ex.getException()); } } } return token; }