List of usage examples for javax.naming.ldap Rdn getValue
public Object getValue()
From source file:edu.jhu.pha.vospace.oauth.AuthorizationServlet.java
private String checkCertificate(HttpServletRequest request) { java.security.cert.X509Certificate[] certs = (java.security.cert.X509Certificate[]) request .getAttribute("javax.servlet.request.X509Certificate"); if (null != certs) { if (certs[0] != null) { String dn = certs[0].getSubjectX500Principal().getName(); try { LdapName ldn = new LdapName(dn); Iterator<Rdn> rdns = ldn.getRdns().iterator(); String org = null, cn = null; while (rdns.hasNext()) { Rdn rdn = (Rdn) rdns.next(); if (rdn.getType().equalsIgnoreCase("O")) org = (String) rdn.getValue(); else if (rdn.getType().equalsIgnoreCase("CN")) cn = (String) rdn.getValue(); }//from ww w . jav a2s .c om if (cn != null) { return cn; } else { logger.error("Error authenticating the user: cn not found in certificate."); throw new PermissionDeniedException("401 Unauthorized"); } } catch (javax.naming.InvalidNameException e) { } } } return null; }
From source file:com.zimbra.cs.service.authenticator.CertUtil.java
private String getSubjectAttr(String needAttrName, String needAttrOid) { String subjectDN = getSubjectDN(); try {// ww w . j a v a2 s .c om LdapName dn = new LdapName(subjectDN); List<Rdn> rdns = dn.getRdns(); for (Rdn rdn : rdns) { String type = rdn.getType(); boolean isOid = type.contains("."); boolean matched = (isOid ? type.equals(needAttrOid) : type.equals(needAttrName)); if (matched) { Object value = rdn.getValue(); if (value == null) { continue; } if (isOid) { byte[] bytes = (byte[]) value; ASN1InputStream decoder = null; try { decoder = new ASN1InputStream(bytes); DEREncodable encoded = decoder.readObject(); DERIA5String str = DERIA5String.getInstance(encoded); return str.getString(); } catch (IOException e) { ZimbraLog.account.warn(LOG_PREFIX + "unable to decode " + type, e); } finally { ByteUtil.closeStream(decoder); } } else { return value.toString(); } } } } catch (InvalidNameException e) { ZimbraLog.account.warn(LOG_PREFIX + "Invalid subject dn value" + subjectDN, e); } return null; }
From source file:controller.CCInstance.java
public String getCertificateProperty(X500Name x500name, String property) { String cn = ""; LdapName ldapDN = null;/*ww w . j av a 2s . c om*/ try { ldapDN = new LdapName(x500name.toString()); } catch (InvalidNameException ex) { java.util.logging.Logger.getLogger(MultipleValidationDialog.class.getName()).log(Level.SEVERE, null, ex); } for (Rdn rdn : ldapDN.getRdns()) { if (rdn.getType().equals(property)) { cn = rdn.getValue().toString(); } } return cn; }
From source file:org.jahia.services.usermanager.ldap.LDAPUserGroupProvider.java
/** * Retrieve the search attribute from a dn. If the dn does'nt contains the search attribute null is returned * * @param dn// w ww . j a v a 2s.c om * @param isUser * @return */ private String getNameFromDn(String dn, boolean isUser) { LdapName ln = LdapUtils.newLdapName(dn); for (Rdn rdn : ln.getRdns()) { if (rdn.getType().equalsIgnoreCase( isUser ? userConfig.getUidSearchAttribute() : groupConfig.getSearchAttribute())) { return rdn.getValue().toString(); } } return null; }
From source file:com.evolveum.midpoint.testing.model.client.sample.TestExchangeConnector.java
private String distributionGroupOU() throws InvalidNameException { LdapName container = new LdapName(getContainer()); List<String> ous = new ArrayList<>(); List<String> dcs = new ArrayList<>(); String retval = ""; for (Rdn rdn : container.getRdns()) { if (rdn.getType().equalsIgnoreCase("OU")) { ous.add(rdn.getValue().toString()); } else if (rdn.getType().equalsIgnoreCase("DC")) { dcs.add(rdn.getValue().toString()); }//from ww w . ja va2 s.c om } for (int i = dcs.size() - 1; i >= 0; i--) { if (!retval.isEmpty()) { retval += "."; } retval += dcs.get(i); } for (int i = 0; i < ous.size(); i++) { retval += "/" + ous.get(i); } return retval; }
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) */// ww w . j a v a 2 s .c o m 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.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); }// w w w . ja v a 2 s. c om 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 www . ja v a 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; }
From source file:org.apache.syncope.client.console.wicket.markup.html.form.preview.BinaryCertPreviewer.java
@Override public Component preview(final byte[] uploadedBytes) { Label commonNameLabel = new Label("certCommonName", new Model<>()); if (uploadedBytes.length == 0) { LOG.info("Enpty certificate"); return commonNameLabel; }//from w w w . ja v a 2 s.c o m try (ByteArrayInputStream certificateStream = new ByteArrayInputStream(uploadedBytes)) { X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(certificateStream); StringBuilder commonNameBuilder = new StringBuilder("cn="); LdapName ldapName = new LdapName(certificate.getIssuerDN().getName()); for (Rdn rdn : ldapName.getRdns()) { if ("CN".equalsIgnoreCase(rdn.getType())) { commonNameBuilder .append(rdn.getValue() == null ? StringUtils.EMPTY : rdn.getValue().toString()); } } commonNameLabel.setDefaultModelObject(commonNameBuilder.toString()); } catch (Exception e) { LOG.error("Error evaluating certificate file", e); commonNameLabel.setDefaultModelObject(getString(Constants.ERROR)); } return this.addOrReplace(commonNameLabel); }
From source file:org.apache.syncope.console.wicket.markup.html.form.preview.BinaryCertPreviewer.java
@Override public Component preview() { final Label commonNameLabel = new Label("certCommonName", new Model<String>()); final ByteArrayInputStream certificateStream = new ByteArrayInputStream(uploadedBytes); try {//w w w. jav a 2 s . c o m final X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(certificateStream); final StringBuilder commonNameBuilder = new StringBuilder("cn="); final LdapName ldapName = new LdapName(certificate.getIssuerDN().getName()); for (Rdn rdn : ldapName.getRdns()) { if ("CN".equalsIgnoreCase(rdn.getType())) { commonNameBuilder .append(rdn.getValue() == null ? StringUtils.EMPTY : rdn.getValue().toString()); } } commonNameLabel.setDefaultModelObject(commonNameBuilder.toString()); } catch (Exception e) { LOG.error("Error evaluating certificate file", e); throw new IllegalArgumentException("Error evaluating certificate file", e); } finally { IOUtils.closeQuietly(certificateStream); } return this.add(commonNameLabel); }