List of usage examples for javax.xml XMLConstants FEATURE_SECURE_PROCESSING
String FEATURE_SECURE_PROCESSING
To view the source code for javax.xml XMLConstants FEATURE_SECURE_PROCESSING.
Click Source Link
From source file:org.wso2.carbon.apimgt.impl.SAMLGroupIDExtractorImpl.java
public String getGroupingIdentifiers(String loginResponse) { if (log.isDebugEnabled()) { log.debug("Login response " + loginResponse); }//w w w . j a v a2 s. co m ByteArrayInputStream samlResponseStream = null; DocumentBuilder docBuilder; String username = ""; String organization = ""; try { APIManagerConfiguration config = ServiceReferenceHolder.getInstance() .getAPIManagerConfigurationService().getAPIManagerConfiguration(); String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI); if (StringUtils.isBlank(claim)) { claim = "http://wso2.org/claims/organization"; } samlResponseStream = getByteArrayInputStream(loginResponse); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); builderFactory.setNamespaceAware(true); docBuilder = builderFactory.newDocumentBuilder(); Document document = docBuilder.parse(samlResponseStream); Element element = document.getDocumentElement(); UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element); Response response = (Response) unmarshaller.unmarshall(element); List<Assertion> assertions = response.getAssertions(); if (assertions != null && assertions.size() > 0) { Subject subject = assertions.get(0).getSubject(); if (subject != null) { if (subject.getNameID() != null) { username = subject.getNameID().getValue(); } } } RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService(); String tenantDomain = MultitenantUtils.getTenantDomain(username); int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId); UserStoreManager manager = realm.getUserStoreManager(); organization = manager.getUserClaimValue(MultitenantUtils.getTenantAwareUsername(username), claim, null); if (log.isDebugEnabled()) { log.debug("User organization " + organization); } if (organization != null) { organization = tenantDomain + "/" + organization.trim(); } } catch (ParserConfigurationException e) { String msg = "Error while parsing SAML Assertion"; log.error(msg, e); } catch (UnmarshallingException e) { String msg = "Error while unmarshalling the SAML Assertion"; log.error(msg, e); } catch (SAXException e) { String msg = "Parsing exception occur while unmarshalling the SAML Assertion"; log.error(msg, e); } catch (IOException e) { String msg = "IO exception happen while unmarshalling the SAML Assertion"; log.error(msg, e); } catch (UserStoreException e) { log.error("User store exception occurred for user" + username, e); } catch (org.wso2.carbon.user.api.UserStoreException e) { log.error("Error while checking user existence for " + username, e); } finally { if (samlResponseStream != null) { try { samlResponseStream.close(); } catch (IOException e) { //Ignore log.error("ERROR_CLOSING_STREAM"); } } } return organization; }
From source file:org.wso2.carbon.apimgt.impl.SAMLGroupIDExtractorImpl.java
@Override public String[] getGroupingIdentifierList(String loginResponse) { if (log.isDebugEnabled()) { log.debug("Login response " + loginResponse); }/*from w w w. j a v a 2 s. co m*/ ByteArrayInputStream samlResponseStream = null; DocumentBuilder docBuilder; String username = ""; String organization = ""; String[] groupIdArray = null; try { APIManagerConfiguration config = ServiceReferenceHolder.getInstance() .getAPIManagerConfigurationService().getAPIManagerConfiguration(); String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI); if (StringUtils.isBlank(claim)) { claim = "http://wso2.org/claims/organization"; } samlResponseStream = getByteArrayInputStream(loginResponse); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); builderFactory.setNamespaceAware(true); docBuilder = builderFactory.newDocumentBuilder(); Document document = docBuilder.parse(samlResponseStream); Element element = document.getDocumentElement(); UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element); Response response = (Response) unmarshaller.unmarshall(element); List<Assertion> assertions = response.getAssertions(); if (assertions != null && assertions.size() > 0) { Subject subject = assertions.get(0).getSubject(); if (subject != null) { if (subject.getNameID() != null) { username = subject.getNameID().getValue(); } } } String isSAML2Enabled = System.getProperty(APIConstants.READ_ORGANIZATION_FROM_SAML_ASSERTION); if (!StringUtils.isEmpty(isSAML2Enabled) && Boolean.parseBoolean(isSAML2Enabled)) { organization = getOrganizationFromSamlAssertion(assertions); } else { RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService(); String tenantDomain = MultitenantUtils.getTenantDomain(username); int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId); UserStoreManager manager = realm.getUserStoreManager(); organization = manager.getUserClaimValue(MultitenantUtils.getTenantAwareUsername(username), claim, null); } if (log.isDebugEnabled()) { log.debug("User organization " + organization); } if (organization != null) { if (organization.contains(",")) { groupIdArray = organization.split(","); for (int i = 0; i < groupIdArray.length; i++) { groupIdArray[i] = groupIdArray[i].toString().trim(); } } else { organization = organization.trim(); groupIdArray = new String[] { organization }; } } else { // If claim is null then returning a empty string groupIdArray = new String[] {}; } } catch (ParserConfigurationException e) { String msg = "Error while parsing SAML Assertion"; log.error(msg, e); } catch (UnmarshallingException e) { String msg = "Error while unmarshalling the SAML Assertion"; log.error(msg, e); } catch (SAXException e) { String msg = "Parsing exception occur while unmarshalling the SAML Assertion"; log.error(msg, e); } catch (IOException e) { String msg = "IO exception happen while unmarshalling the SAML Assertion"; log.error(msg, e); } catch (UserStoreException e) { log.error("User store exception occurred for user" + username, e); } catch (org.wso2.carbon.user.api.UserStoreException e) { log.error("Error while checking user existence for " + username, e); } finally { if (samlResponseStream != null) { try { samlResponseStream.close(); } catch (IOException e) { //Ignore log.error("ERROR_CLOSING_STREAM"); } } } return groupIdArray; }
From source file:org.wso2.carbon.apimgt.impl.utils.APIUtil.java
/** * @param tenantId/* www .j ava2s .c om*/ * @throws APIManagementException */ public static void createSelfSignUpRoles(int tenantId) throws APIManagementException { try { RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService(); UserRegistry govRegistry = registryService.getGovernanceSystemRegistry(tenantId); if (govRegistry.resourceExists(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION)) { Resource resource = govRegistry.get(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION); InputStream content = resource.getContentStream(); DocumentBuilderFactory factory = getSecuredDocumentBuilder(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder parser = factory.newDocumentBuilder(); Document dc = parser.parse(content); boolean enableSignup = Boolean .parseBoolean(dc.getElementsByTagName(APIConstants.SELF_SIGN_UP_REG_ENABLED).item(0) .getFirstChild().getNodeValue()); String signUpDomain = dc.getElementsByTagName(APIConstants.SELF_SIGN_UP_REG_DOMAIN_ELEM).item(0) .getFirstChild().getNodeValue(); if (enableSignup) { int roleLength = dc.getElementsByTagName(APIConstants.SELF_SIGN_UP_REG_ROLE_NAME_ELEMENT) .getLength(); for (int i = 0; i < roleLength; i++) { String roleName = dc.getElementsByTagName(APIConstants.SELF_SIGN_UP_REG_ROLE_NAME_ELEMENT) .item(i).getFirstChild().getNodeValue(); boolean isExternalRole = Boolean.parseBoolean( dc.getElementsByTagName(APIConstants.SELF_SIGN_UP_REG_ROLE_IS_EXTERNAL).item(i) .getFirstChild().getNodeValue()); if (roleName != null) { // If isExternalRole==false ;create the subscriber role as an internal role if (isExternalRole && signUpDomain != null) { roleName = signUpDomain.toUpperCase() + CarbonConstants.DOMAIN_SEPARATOR + roleName; } else { roleName = UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR + roleName; } createSubscriberRole(roleName, tenantId); } } } } if (log.isDebugEnabled()) { log.debug("Adding Self signup configuration to the tenant's registry"); } } catch (RegistryException e) { throw new APIManagementException("Error while getting Self signup role information from the registry", e); } catch (ParserConfigurationException e) { throw new APIManagementException("Error while getting Self signup role information from the registry", e); } catch (SAXException e) { throw new APIManagementException("Error while getting Self signup role information from the registry", e); } catch (IOException e) { throw new APIManagementException("Error while getting Self signup role information from the registry", e); } }
From source file:org.wso2.carbon.apimgt.webapp.publisher.WebappPublisherUtil.java
public static Document convertToDocument(File file) throws WebappPublisherConfigurationFailedException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);//from w w w.j a v a 2s . c o m try { factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder docBuilder = factory.newDocumentBuilder(); return docBuilder.parse(file); } catch (Exception e) { throw new WebappPublisherConfigurationFailedException( "Error occurred while parsing file, while converting " + "to a org.w3c.dom.Document", e); } }
From source file:org.wso2.carbon.appmgt.impl.utils.SelfSignUpUtil.java
/** * load configuration from the registry/*from w w w .j ava 2 s . c om*/ * * @param tenantId tenant id * @return * @throws org.wso2.carbon.appmgt.api.AppManagementException */ private static UserRegistrationConfigDTO getSignupConfigurationFromRegistry(int tenantId) throws AppManagementException { UserRegistrationConfigDTO config = null; try { Registry registry = ServiceReferenceHolder.getInstance().getRegistryService() .getGovernanceSystemRegistry(tenantId); if (registry.resourceExists(AppMConstants.SELF_SIGN_UP_CONFIG_LOCATION)) { Resource resource = registry.get(AppMConstants.SELF_SIGN_UP_CONFIG_LOCATION); // build config from registry resource DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder(); String configXml = new String((byte[]) resource.getContent()); InputSource configInputSource = new InputSource(); configInputSource.setCharacterStream(new StringReader(configXml.trim())); Document doc = builder.parse(configInputSource); NodeList nodes = doc.getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROOT); if (nodes.getLength() > 0) { config = new UserRegistrationConfigDTO(); config.setSignUpDomain(((Element) nodes.item(0)) .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_DOMAIN_ELEM).item(0) .getTextContent()); // set tenant admin credentials config.setAdminUserName( ((Element) nodes.item(0)).getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_USERNAME) .item(0).getTextContent()); config.setAdminPassword( ((Element) nodes.item(0)).getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_PASSWORD) .item(0).getTextContent()); config.setSignUpEnabled(Boolean.parseBoolean( ((Element) nodes.item(0)).getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ENABLED) .item(0).getTextContent())); // iterate through sign-up role list Element roleListParent = (Element) ((Element) nodes.item(0)) .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLES_ELEM).item(0); NodeList rolesEl = roleListParent .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLE_ELEM); for (int i = 0; i < rolesEl.getLength(); i++) { Element tmpEl = (Element) rolesEl.item(i); String tmpRole = tmpEl .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLE_NAME_ELEMENT).item(0) .getTextContent(); boolean tmpIsExternal = Boolean.parseBoolean( tmpEl.getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLE_IS_EXTERNAL).item(0) .getTextContent()); String permissions = null; NodeList permissionsNodeList = tmpEl.getElementsByTagName("Permissions"); if (permissionsNodeList.item(0) != null) { permissions = permissionsNodeList.item(0).getTextContent(); } String[] permissionList = null; permissionList = permissions != null ? permissions.split(",") : new String[] { "/permission/admin/login", "/permission/admin/manage/webapp/subscribe" }; SignUpRole signUpRole = new SignUpRole(); signUpRole.setRoleName(tmpRole); signUpRole.setExternalRole(tmpIsExternal); signUpRole.setPermissionsList(permissionList); config.getSignUpRoles().add(signUpRole); } } } } catch (RegistryException e) { throw new AppManagementException( "Error while reading sign-up configuration file in registry location : " + AppMConstants.SELF_SIGN_UP_CONFIG_LOCATION, e); } catch (ParserConfigurationException e) { throw new AppManagementException("Error while building sign-up configuration file in : " + AppMConstants.SELF_SIGN_UP_CONFIG_LOCATION, e); } catch (SAXException e) { throw new AppManagementException( "Error while parsing sign-up configuration in : " + AppMConstants.SELF_SIGN_UP_CONFIG_LOCATION, e); } catch (IOException e) { throw new AppManagementException( "Error while parsing sign-up configuration in : " + AppMConstants.SELF_SIGN_UP_CONFIG_LOCATION, e); } return config; }
From source file:org.wso2.carbon.appmgt.migration.util.ResourceUtil.java
private static DocumentBuilder getDocumentBuilder(String fileName) throws APPMMigrationException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true);/*from w w w . j a v a 2s. c om*/ DocumentBuilder docBuilder = null; try { docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); docBuilder = docFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { ResourceUtil.handleException("Error occurred while trying to build the " + fileName + " xml document", e); } return docBuilder; }
From source file:org.wso2.carbon.bpmn.core.types.datatypes.xml.Utils.java
/** * Create DocumentBuilderFactory with the XXE and XEE prevention measurements. * * @return DocumentBuilderFactory instance *//*from w w w.ja v a 2 s . c o m*/ public static DocumentBuilderFactory getSecuredDocumentBuilder() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setXIncludeAware(false); dbf.setExpandEntityReferences(false); try { dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false); dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false); dbf.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (ParserConfigurationException e) { log.error("Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE + " or " + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or " + Constants.LOAD_EXTERNAL_DTD_FEATURE + " or secure-processing."); } SecurityManager securityManager = new SecurityManager(); securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT); dbf.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager); return dbf; }
From source file:org.wso2.carbon.certificate.mgt.core.util.CertificateManagerUtil.java
public static Document convertToDocument(File file) throws CertificateManagementException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);//from w w w .j a va 2s . c o m try { factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); DocumentBuilder docBuilder = factory.newDocumentBuilder(); return docBuilder.parse(file); } catch (Exception e) { throw new CertificateManagementException("Error occurred while parsing file, while converting " + "to a org.w3c.dom.Document : " + e.getMessage(), e); } }
From source file:org.wso2.carbon.dataservices.core.XSLTTransformer.java
/** * This method provides a secured document builder which will secure XXE attacks. * * @param setIgnoreComments whether to set setIgnoringComments in DocumentBuilderFactory. * @return DocumentBuilder// w w w . j a v a 2 s. c om * @throws javax.xml.parsers.ParserConfigurationException */ private static DocumentBuilder getSecuredDocumentBuilder(boolean setIgnoreComments) throws ParserConfigurationException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setIgnoringComments(setIgnoreComments); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setExpandEntityReferences(false); documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { throw new SAXException("Possible XML External Entity (XXE) attack. Skip resolving entity"); } }); return documentBuilder; }
From source file:org.wso2.carbon.datasource.utils.DataSourceUtils.java
/** * This method provides a secured document builder which will secure XXE attacks. * * @param setIgnoreComments whether to set setIgnoringComments in DocumentBuilderFactory. * @return DocumentBuilder// w w w .j a v a 2 s . c o m * @throws ParserConfigurationException */ private static DocumentBuilder getSecuredDocumentBuilder(boolean setIgnoreComments) throws ParserConfigurationException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setIgnoringComments(setIgnoreComments); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setExpandEntityReferences(false); documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setEntityResolver((publicId, systemId) -> { throw new SAXException("Possible XML External Entity (XXE) attack. Skip resolving entity"); }); return documentBuilder; }