InfraKerberosHostValidator.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. package org.apache.ambari.infra.security;
  20. import org.apache.commons.collections.CollectionUtils;
  21. import org.apache.commons.collections.MapUtils;
  22. import org.apache.hadoop.security.authentication.server.AuthenticationToken;
  23. import org.apache.hadoop.security.authentication.util.KerberosName;
  24. import java.security.Principal;
  25. import java.util.Map;
  26. import java.util.Set;
  27. /**
  28. * Validate that the user has the right access based on the hostname in the kerberos principal
  29. */
  30. public class InfraKerberosHostValidator {
  31. public boolean validate(Principal principal, Map<String, Set<String>> userVsHosts, Map<String, String> userVsHostRegex) {
  32. if (principal instanceof AuthenticationToken) {
  33. AuthenticationToken authenticationToken = (AuthenticationToken) principal;
  34. KerberosName kerberosName = new KerberosName(authenticationToken.getName());
  35. String hostname = kerberosName.getHostName();
  36. String serviceUserName = kerberosName.getServiceName();
  37. if (MapUtils.isNotEmpty(userVsHostRegex)) {
  38. String regex = userVsHostRegex.get(serviceUserName);
  39. return hostname.matches(regex);
  40. }
  41. if (MapUtils.isNotEmpty(userVsHosts)) {
  42. Set<String> hosts = userVsHosts.get(serviceUserName);
  43. if (CollectionUtils.isNotEmpty(hosts)) {
  44. return hosts.contains(hostname);
  45. }
  46. }
  47. }
  48. return true;
  49. }
  50. }