List of usage examples for javax.naming.ldap LdapName LdapName
public LdapName(List<Rdn> rdns)
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
/** * Works around a bug in the JDK DN parsing. If an RDN has trailing escaped whitespace in the format "\\20" then * LdapName would normally strip this. This method works around this by replacing "\\20" with "\\ " and "\\0D" with * "\\\r".//w ww .j av a 2 s . c o m * * @param dn * the DN * @return the parsed ldap name * @throws javax.naming.InvalidNameException * if the DN is invalid */ private static LdapName fixedLdapName(String dn) throws InvalidNameException { // Optimization for DNs without escapes in them if (dn.indexOf('\\') == -1) { return new LdapName(dn); } StringBuilder fixed = new StringBuilder(dn.length()); int length = dn.length(); for (int i = 0; i < length; i++) { char c = dn.charAt(i); char c1, c2; if (c == '\\') { if (i + 2 < length && Character.isLetterOrDigit(c1 = dn.charAt(i + 1)) && Character.isLetterOrDigit(c2 = dn.charAt(i + 2))) { if (c1 == '2' && c2 == '0') { fixed.append("\\ "); } else if (c1 == '0' && c2 == 'D') { fixed.append("\\\r"); } else { fixed.append(dn, i, i + 3); } i += 2; } else if (i + 1 < length) { fixed.append(dn, i, i + 2); i += 1; } else { fixed.append(c); } } else { fixed.append(c); } } return new LdapName(fixed.toString()); }
From source file:org.jahia.services.usermanager.ldap.LDAPUserGroupProvider.java
/** * Try to guess if the given dn is a user or a group * * @param dn/* www. ja v a2s. co m*/ * @return * @throws InvalidNameException */ private Boolean guessUserOrGroupFromDN(String dn) throws InvalidNameException { Boolean isUser = null; final LdapName memberLdapName = LdapUtils.newLdapName(dn); if (memberLdapName.startsWith(new LdapName(userConfig.getUidSearchName()))) { // it's a user isUser = distinctBase ? true : null; } else if (memberLdapName.startsWith(new LdapName(groupConfig.getSearchName()))) { // it's a group isUser = distinctBase ? false : null; } return isUser; }
From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java
/** * Iterates through the characters of the given distinguished name to escape special characters * * @param dn the distinguished name to process * @return the distinguished name with escaped characters * @see #escapeCharacters(String, java.util.Set, Character) */// w ww.j a v a 2s. c om protected String escapeDNCharacters(String dn) throws InvalidNameException { if ((dn == null) || dn.isEmpty()) { return dn; } else { LdapName name = new LdapName(dn); List<Rdn> rdns = name.getRdns(); if ((rdns == null) || rdns.isEmpty()) { throw new InvalidNameException(String.format("One or more RDNs are expected for a DN of %s", dn)); } StringBuilder builder = new StringBuilder(); for (Rdn rdn : rdns) { builder.insert(0, String.format(",%s=%s", rdn.getType(), escapeCharacters((String) rdn.getValue(), SPECIAL_DN_CHARACTERS, DN_ESCAPE_CHARACTER))); } return builder.substring(1); } }
From source file:org.apache.archiva.redback.common.ldap.connection.LdapConnectionConfiguration.java
public LdapConnectionConfiguration(String hostname, int port, String baseDn, String contextFactory, String bindDn, String password, String authenticationMethod, Properties extraProperties) throws InvalidNameException, LdapException { this.hostname = hostname; this.port = port; if (baseDn != null) { this.baseDn = new LdapName(baseDn); }//from w ww.ja v a 2 s . c o m if (bindDn != null) { this.bindDn = new LdapName(bindDn); } this.contextFactory = contextFactory; this.password = password; this.authenticationMethod = authenticationMethod; this.extraProperties = extraProperties; check(); }
From source file:org.apache.archiva.redback.common.ldap.connection.LdapConnectionConfiguration.java
public void setBaseDn(String baseDn) throws InvalidNameException { if (baseDn != null) { this.baseDn = new LdapName(baseDn); }// ww w. j a v a2s .c o m }
From source file:org.apache.archiva.redback.common.ldap.connection.LdapConnectionConfiguration.java
public void setBindDn(String bindDn) throws InvalidNameException { if (bindDn != null) { this.bindDn = new LdapName(bindDn); }// w ww. j a v a 2 s . c o m }
From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
/** * Gets a Name object that is save for JNDI operations. * <p>/* w ww .j a v a 2s .com*/ * In JNDI we have could use the following classes for names: * <ul> * <li>Dn as String</li> * <li>javax.naming.CompositeName</li> * <li>javax.naming.ldap.LdapName (since Java5)</li> * <li>org.apache.directory.api.ldap.name.LdapDN</li> * </ul> * <p> * There are some drawbacks when using this classes: * <ul> * <li>When passing Dn as String, JNDI doesn't handle slashes '/' correctly. * So we must use a Name object here.</li> * <li>With CompositeName we have the same problem with slashes '/'.</li> * <li>When using LdapDN from shared-ldap, JNDI uses the toString() method * and LdapDN.toString() returns the normalized ATAV, but we need the * user provided ATAV.</li> * <li>When using LdapName for the empty Dn (Root DSE) JNDI _sometimes_ throws * an Exception (java.lang.IndexOutOfBoundsException: Posn: -1, Size: 0 * at javax.naming.ldap.LdapName.getPrefix(LdapName.java:240)).</li> * <li>Using LdapDN for the RootDSE doesn't work with Apache Harmony because * its JNDI provider only accepts intstances of CompositeName or LdapName.</li> * </ul> * <p> * So we use LdapName as default and the CompositeName for the empty Dn. * * @param name the Dn * * @return the save JNDI name * * @throws InvalidNameException the invalid name exception */ static Name getSaveJndiName(String name) throws InvalidNameException { if (name == null || StringUtils.isEmpty(name)) //$NON-NLS-1$ { return new CompositeName(); } else { return new LdapName(name); } }
From source file:org.apache.nifi.registry.security.util.CertificateUtils.java
/** * Returns true if the two provided DNs are equivalent, regardless of the order of the elements. Returns false if one or both are invalid DNs. * * Example://from w ww . j ava 2 s .co m * * CN=test1, O=testOrg, C=US compared to CN=test1, O=testOrg, C=US -> true * CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test1, C=US -> true * CN=test1, O=testOrg, C=US compared to CN=test2, O=testOrg, C=US -> false * CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test2, C=US -> false * CN=test1, O=testOrg, C=US compared to -> false * compared to -> true * * @param dn1 the first DN to compare * @param dn2 the second DN to compare * @return true if the DNs are equivalent, false otherwise */ public static boolean compareDNs(String dn1, String dn2) { if (dn1 == null) { dn1 = ""; } if (dn2 == null) { dn2 = ""; } if (StringUtils.isEmpty(dn1) || StringUtils.isEmpty(dn2)) { return dn1.equals(dn2); } try { List<Rdn> rdn1 = new LdapName(dn1).getRdns(); List<Rdn> rdn2 = new LdapName(dn2).getRdns(); return rdn1.size() == rdn2.size() && rdn1.containsAll(rdn2); } catch (InvalidNameException e) { logger.warn("Cannot compare DNs: {} and {} because one or both is not a valid DN", dn1, dn2); return false; } }
From source file:org.apache.ranger.biz.AssetMgr.java
public String getLatestRepoPolicy(VXAsset xAsset, List<VXResource> xResourceList, Long updatedTime, X509Certificate[] certchain, boolean httpEnabled, String epoch, String ipAddress, boolean isSecure, String count, String agentId) { if (xAsset == null) { logger.error("Requested repository not found"); throw restErrorUtil.createRESTException("No Data Found.", MessageEnums.DATA_NOT_FOUND); }//from w w w .j a va2 s . co m if (xResourceList == null) { logger.error("ResourceList is found"); throw restErrorUtil.createRESTException("No Data Found.", MessageEnums.DATA_NOT_FOUND); } if (xAsset.getActiveStatus() == RangerCommonEnums.ACT_STATUS_DISABLED) { logger.error("Requested repository is disabled"); throw restErrorUtil.createRESTException("Unauthorized access.", MessageEnums.OPER_NO_EXPORT); } HashMap<String, Object> updatedRepo = new HashMap<String, Object>(); updatedRepo.put("repository_name", xAsset.getName()); XXPolicyExportAudit policyExportAudit = new XXPolicyExportAudit(); policyExportAudit.setRepositoryName(xAsset.getName()); if (agentId != null && !agentId.isEmpty()) { policyExportAudit.setAgentId(agentId); } policyExportAudit.setClientIP(ipAddress); if (epoch != null && !epoch.trim().isEmpty() && !epoch.equalsIgnoreCase("null")) { policyExportAudit.setRequestedEpoch(Long.parseLong(epoch)); } else { policyExportAudit.setRequestedEpoch(0L); } if (!httpEnabled) { if (!isSecure) { policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST); createPolicyAudit(policyExportAudit); throw restErrorUtil.createRESTException("Unauthorized access -" + " only https allowed", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } if (certchain == null || certchain.length == 0) { policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST); createPolicyAudit(policyExportAudit); throw restErrorUtil.createRESTException( "Unauthorized access -" + " unable to get client certificate", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } } Long policyCount = restErrorUtil.parseLong(count, "Invalid value for " + "policyCount", MessageEnums.INVALID_INPUT_DATA, null, "policyCount"); String commonName = null; if (certchain != null) { X509Certificate clientCert = certchain[0]; String dn = clientCert.getSubjectX500Principal().getName(); try { LdapName ln = new LdapName(dn); for (Rdn rdn : ln.getRdns()) { if (rdn.getType().equalsIgnoreCase("CN")) { commonName = rdn.getValue() + ""; break; } } if (commonName == null) { policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST); createPolicyAudit(policyExportAudit); throw restErrorUtil.createRESTException( "Unauthorized access - Unable to find Common Name from [" + dn + "]", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } } catch (InvalidNameException e) { policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST); createPolicyAudit(policyExportAudit); logger.error("Invalid Common Name.", e); throw restErrorUtil.createRESTException("Unauthorized access - Invalid Common Name", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } } if (policyCount == null) { policyCount = 0L; } if (commonName != null) { String config = xAsset.getConfig(); Map<String, String> configMap = jsonUtil.jsonToMap(config); String cnFromConfig = configMap.get("commonNameForCertificate"); if (cnFromConfig == null || !commonName.equalsIgnoreCase(cnFromConfig)) { policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST); createPolicyAudit(policyExportAudit); throw restErrorUtil.createRESTException( "Unauthorized access. expected [" + cnFromConfig + "], found [" + commonName + "]", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } } long epochTime = epoch != null ? Long.parseLong(epoch) : 0; if (epochTime == updatedTime) { int resourceListSz = xResourceList.size(); if (policyCount == resourceListSz) { policyExportAudit.setHttpRetCode(HttpServletResponse.SC_NOT_MODIFIED); createPolicyAudit(policyExportAudit); throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_MODIFIED, "No change since last update", false); } } List<HashMap<String, Object>> resourceList = new ArrayList<HashMap<String, Object>>(); // HDFS Repository if (xAsset.getAssetType() == AppConstants.ASSET_HDFS) { for (VXResource xResource : xResourceList) { HashMap<String, Object> resourceMap = new HashMap<String, Object>(); resourceMap.put("id", xResource.getId()); resourceMap.put("resource", xResource.getName()); resourceMap.put("isRecursive", getBooleanValue(xResource.getIsRecursive())); resourceMap.put("policyStatus", RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus())); // resourceMap.put("isEncrypt", // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt())); populatePermMap(xResource, resourceMap, AppConstants.ASSET_HDFS); List<VXAuditMap> xAuditMaps = xResource.getAuditList(); if (xAuditMaps.size() != 0) { resourceMap.put("audit", 1); } else { resourceMap.put("audit", 0); } resourceList.add(resourceMap); } } else if (xAsset.getAssetType() == AppConstants.ASSET_HIVE) { for (VXResource xResource : xResourceList) { HashMap<String, Object> resourceMap = new HashMap<String, Object>(); resourceMap.put("id", xResource.getId()); resourceMap.put("database_name", xResource.getDatabases()); resourceMap.put("policyStatus", RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus())); resourceMap.put("tablePolicyType", AppConstants.getLabelFor_PolicyType(xResource.getTableType())); resourceMap.put("columnPolicyType", AppConstants.getLabelFor_PolicyType(xResource.getColumnType())); int resourceType = xResource.getResourceType(); if (resourceType == AppConstants.RESOURCE_UDF) { resourceMap.put("udf_name", xResource.getUdfs()); } else if (resourceType == AppConstants.RESOURCE_COLUMN) { resourceMap.put("table_name", xResource.getTables()); resourceMap.put("column_name", xResource.getColumns()); } else if (resourceType == AppConstants.RESOURCE_TABLE) { resourceMap.put("table_name", xResource.getTables()); } populatePermMap(xResource, resourceMap, AppConstants.ASSET_HIVE); List<VXAuditMap> xAuditMaps = xResource.getAuditList(); if (xAuditMaps.size() != 0) { resourceMap.put("audit", 1); } else { resourceMap.put("audit", 0); } resourceList.add(resourceMap); } } else if (xAsset.getAssetType() == AppConstants.ASSET_HBASE) { for (VXResource xResource : xResourceList) { HashMap<String, Object> resourceMap = new HashMap<String, Object>(); resourceMap.put("id", xResource.getId()); resourceMap.put("table_name", xResource.getTables()); resourceMap.put("column_name", xResource.getColumns()); resourceMap.put("column_families", xResource.getColumnFamilies()); resourceMap.put("policyStatus", RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus())); if (xResource.getIsEncrypt() == 1) { resourceMap.put("encrypt", 1); } else { resourceMap.put("encrypt", 0); } // resourceMap.put("isEncrypt", // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt())); populatePermMap(xResource, resourceMap, AppConstants.ASSET_HBASE); List<VXAuditMap> xAuditMaps = xResource.getAuditList(); if (xAuditMaps.size() != 0) { resourceMap.put("audit", 1); } else { resourceMap.put("audit", 0); } resourceList.add(resourceMap); } } else if (xAsset.getAssetType() == AppConstants.ASSET_KNOX) { for (VXResource xResource : xResourceList) { HashMap<String, Object> resourceMap = new HashMap<String, Object>(); resourceMap.put("id", xResource.getId()); resourceMap.put("topology_name", xResource.getTopologies()); resourceMap.put("service_name", xResource.getServices()); resourceMap.put("policyStatus", RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus())); if (xResource.getIsEncrypt() == 1) { resourceMap.put("encrypt", 1); } else { resourceMap.put("encrypt", 0); } // resourceMap.put("isEncrypt", // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt())); populatePermMap(xResource, resourceMap, AppConstants.ASSET_KNOX); List<VXAuditMap> xAuditMaps = xResource.getAuditList(); if (xAuditMaps.size() != 0) { resourceMap.put("audit", 1); } else { resourceMap.put("audit", 0); } resourceList.add(resourceMap); } } else if (xAsset.getAssetType() == AppConstants.ASSET_STORM) { for (VXResource xResource : xResourceList) { HashMap<String, Object> resourceMap = new HashMap<String, Object>(); resourceMap.put("id", xResource.getId()); resourceMap.put("topology_name", xResource.getTopologies()); resourceMap.put("policyStatus", RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus())); if (xResource.getIsEncrypt() == 1) { resourceMap.put("encrypt", 1); } else { resourceMap.put("encrypt", 0); } populatePermMap(xResource, resourceMap, AppConstants.ASSET_STORM); List<VXAuditMap> xAuditMaps = xResource.getAuditList(); if (xAuditMaps.size() != 0) { resourceMap.put("audit", 1); } else { resourceMap.put("audit", 0); } resourceList.add(resourceMap); } } else { policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST); createPolicyAudit(policyExportAudit); throw restErrorUtil.createRESTException("The operation isn't yet supported for the repository", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } policyCount = Long.valueOf(resourceList.size()); updatedRepo.put("last_updated", updatedTime); updatedRepo.put("policyCount", policyCount); updatedRepo.put("acl", resourceList); String updatedPolicyStr = jsonUtil.readMapToString(updatedRepo); // File file = null; // try { // file = jsonUtil.writeMapToFile(updatedRepo, repository); // } catch (JsonGenerationException e) { // logger.error("Error exporting policies for repository : " // + repository, e); // } catch (JsonMappingException e) { // logger.error("Error exporting policies for repository : " // + repository, e); // } catch (IOException e) { // logger.error("Error exporting policies for repository : " // + repository, e); // } policyExportAudit.setHttpRetCode(HttpServletResponse.SC_OK); createPolicyAudit(policyExportAudit); return updatedPolicyStr; }
From source file:org.apache.ranger.common.ServiceUtil.java
public boolean isValidateHttpsAuthentication(String serviceName, HttpServletRequest request) { boolean isValidAuthentication = false; boolean httpEnabled = PropertiesUtil.getBooleanProperty("ranger.service.http.enabled", true); X509Certificate[] certchain = (X509Certificate[]) request .getAttribute("javax.servlet.request.X509Certificate"); String ipAddress = request.getHeader("X-FORWARDED-FOR"); if (ipAddress == null) { ipAddress = request.getRemoteAddr(); }//from w w w.j a va 2 s . c o m boolean isSecure = request.isSecure(); if (serviceName == null || serviceName.isEmpty()) { LOG.error("ServiceName not provided"); throw restErrorUtil.createRESTException("Unauthorized access.", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } RangerService service = null; try { service = svcStore.getServiceByName(serviceName); } catch (Exception e) { LOG.error("Requested Service not found. serviceName=" + serviceName); throw restErrorUtil.createRESTException("Service:" + serviceName + " not found", MessageEnums.DATA_NOT_FOUND); } if (service == null) { LOG.error("Requested Service not found. serviceName=" + serviceName); throw restErrorUtil.createRESTException("Service:" + serviceName + " not found", MessageEnums.DATA_NOT_FOUND); } if (!service.getIsEnabled()) { LOG.error("Requested Service is disabled. serviceName=" + serviceName); throw restErrorUtil.createRESTException("Unauthorized access.", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); } if (!httpEnabled) { if (!isSecure) { LOG.error("Unauthorized access. Only https is allowed. serviceName=" + serviceName); throw restErrorUtil.createRESTException("Unauthorized access -" + " only https allowed", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } if (certchain == null || certchain.length == 0) { LOG.error("Unauthorized access. Unable to get client certificate. serviceName=" + serviceName); throw restErrorUtil.createRESTException( "Unauthorized access -" + " unable to get client certificate", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } // Check if common name is found in service config Map<String, String> configMap = service.getConfigs(); String cnFromConfig = configMap.get("commonNameForCertificate"); if (cnFromConfig == null || "".equals(cnFromConfig.trim())) { LOG.error( "Unauthorized access. No common name for certificate set. Please check your service config"); throw restErrorUtil.createRESTException( "Unauthorized access. No common name for certificate set. Please check your service config", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } String cnFromConfigForTest = cnFromConfig; boolean isRegEx = cnFromConfig.toLowerCase().startsWith(REGEX_PREFIX_STR); if (isRegEx) { cnFromConfigForTest = cnFromConfig.substring(REGEX_PREFIX_STR_LENGTH); } // Perform SAN validation try { Collection<List<?>> subjectAltNames = certchain[0].getSubjectAlternativeNames(); if (subjectAltNames != null) { for (List<?> sanItem : subjectAltNames) { if (sanItem.size() == 2) { Integer sanType = (Integer) sanItem.get(0); String sanValue = (String) sanItem.get(1); if ((sanType == 2 || sanType == 7) && (matchNames(sanValue, cnFromConfigForTest, isRegEx))) { if (LOG.isDebugEnabled()) LOG.debug("Client Cert verification successful, matched SAN:" + sanValue); isValidAuthentication = true; break; } } } } } catch (Throwable e) { LOG.error("Unauthorized access. Error getting SAN from certificate", e); throw restErrorUtil.createRESTException( "Unauthorized access - Error getting SAN from client certificate", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } // Perform common name validation only if SAN validation did not succeed if (!isValidAuthentication) { String commonName = null; if (certchain != null) { X509Certificate clientCert = certchain[0]; String dn = clientCert.getSubjectX500Principal().getName(); try { LdapName ln = new LdapName(dn); for (Rdn rdn : ln.getRdns()) { if (rdn.getType().equalsIgnoreCase("CN")) { commonName = rdn.getValue() + ""; break; } } if (commonName == null) { LOG.error("Unauthorized access. CName is null. serviceName=" + serviceName); throw restErrorUtil.createRESTException( "Unauthorized access - Unable to find Common Name from [" + dn + "]", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } } catch (InvalidNameException e) { LOG.error("Invalid Common Name. CName=" + commonName + ", serviceName=" + serviceName, e); throw restErrorUtil.createRESTException("Unauthorized access - Invalid Common Name", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } } if (commonName != null) { if (matchNames(commonName, cnFromConfigForTest, isRegEx)) { if (LOG.isDebugEnabled()) LOG.debug("Client Cert verification successful, matched CN " + commonName + " with " + cnFromConfigForTest + ", wildcard match = " + isRegEx); isValidAuthentication = true; } if (!isValidAuthentication) { LOG.error("Unauthorized access. expected [" + cnFromConfigForTest + "], found [" + commonName + "], serviceName=" + serviceName); throw restErrorUtil.createRESTException("Unauthorized access. expected [" + cnFromConfigForTest + "], found [" + commonName + "]", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } } } } else { isValidAuthentication = true; } return isValidAuthentication; }