Java Code Examples for org.wso2.carbon.identity.core.util.IdentityUtil#getSecuredDocumentBuilderFactory()

The following examples show how to use org.wso2.carbon.identity.core.util.IdentityUtil#getSecuredDocumentBuilderFactory() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PAPPolicyReader.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private PAPPolicyReader(PolicyFinder policyFinder) {

        this.policyFinder = policyFinder;

        // create the factory
        DocumentBuilderFactory documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory();
        documentBuilderFactory.setIgnoringComments(true);

        // now use the factory to create the document builder
        try {
            builder = documentBuilderFactory.newDocumentBuilder();
            builder.setErrorHandler(this);
        } catch (ParserConfigurationException pce) {
            throw new IllegalArgumentException("Failed to create the DocumentBuilder. : ", pce);
        }
    }
 
Example 2
Source File: WSXACMLMessageReceiver.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Constructing the SAML or XACML Objects from a String
 *
 * @param xmlString Decoded SAML or XACML String
 * @return SAML or XACML Object
 * @throws org.wso2.carbon.identity.entitlement.EntitlementException
 */
public XMLObject unmarshall(String xmlString) throws EntitlementException {

    try {
        doBootstrap();
        DocumentBuilderFactory documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory();

        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(new ByteArrayInputStream(xmlString.trim().getBytes()));
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = XMLObjectProviderRegistrySupport.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        return unmarshaller.unmarshall(element);
    } catch (Exception e) {
        log.error("Error in constructing XML(SAML or XACML) Object from the encoded String", e);
        throw new EntitlementException("Error in constructing XML(SAML or XACML) from the encoded String ", e);
    }
}
 
Example 3
Source File: XACMLBasedRuleHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private boolean evaluateXACMLResponse(String xacmlResponse) throws IdentityProvisioningException {

        try {
            DocumentBuilderFactory documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory();
            DocumentBuilder db = documentBuilderFactory.newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xacmlResponse));
            Document doc = db.parse(is);

            String decision = "";
            NodeList decisionNode = doc.getDocumentElement().getElementsByTagName(
                            ProvisioningRuleConstanats.XACML_RESPONSE_DECISION_NODE);
            if (decisionNode != null && decisionNode.item(0) != null) {
                decision = decisionNode.item(0).getTextContent();
            }
            if (decision.equalsIgnoreCase(EntitlementPolicyConstants.RULE_EFFECT_PERMIT)
                || decision.equalsIgnoreCase(EntitlementPolicyConstants.RULE_EFFECT_NOT_APPLICABLE)) {
                return true;
            }
        } catch (ParserConfigurationException | SAXException | IOException e) {
            throw new IdentityProvisioningException("Exception occurred while xacmlResponse processing", e);
        }
        return false;
    }
 
Example 4
Source File: DefaultAuthSeqMgtServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private String marshalDefaultAuthSeq(LocalAndOutboundAuthenticationConfig sequence, String tenantDomain)
        throws DefaultAuthSeqMgtException {

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(LocalAndOutboundAuthenticationConfig.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        DocumentBuilderFactory docBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory();
        Document document = docBuilderFactory.newDocumentBuilder().newDocument();
        marshaller.marshal(sequence, document);
        TransformerFactory transformerFactory = IdentityUtil.getSecuredTransformerFactory();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS,
                "AuthenticationScript inboundConfiguration");
        StringWriter stringBuilder = new StringWriter();
        StreamResult result = new StreamResult(stringBuilder);
        transformer.transform(new DOMSource(document), result);
        return stringBuilder.getBuffer().toString();
    } catch (JAXBException | ParserConfigurationException | TransformerException e) {
        throw new DefaultAuthSeqMgtException("Error in marshalling default authentication sequence in: " +
                tenantDomain, e);
    }
}
 
Example 5
Source File: ApplicationManagementServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private String marshalSPTemplate(ServiceProvider serviceProvider, String tenantDomain)
        throws IdentityApplicationManagementException {

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(ServiceProvider.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        DocumentBuilderFactory docBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory();
        Document document = docBuilderFactory.newDocumentBuilder().newDocument();
        marshaller.marshal(serviceProvider, document);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS,
                "AuthenticationScript inboundConfiguration");
        StringWriter stringBuilder = new StringWriter();
        StreamResult result = new StreamResult(stringBuilder);
        transformer.transform(new DOMSource(document), result);
        return stringBuilder.getBuffer().toString();
    } catch (JAXBException | ParserConfigurationException | TransformerException e) {
        throw new IdentityApplicationManagementException(String.format("Error in exporting Service Provider " +
                "template from SP %s@%s", serviceProvider.getApplicationName(), tenantDomain), e);
    }
}
 
Example 6
Source File: WorkflowManagementUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Un-marshall given string to given class type
 *
 * @param xmlString XML String that is validated against its XSD
 * @param classType Root Class Name to convert XML String to Object
 * @param <T>       Root Class that should return
 * @return Instance of T
 * @throws JAXBException
 */
public static <T> T unmarshalXML(String xmlString, Class<T> classType) throws JAXBException {
    T t = null;
    if (xmlString != null) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xmlString.getBytes());
        JAXBContext jaxbContext = JAXBContext.newInstance(classType);

        try {
            DocumentBuilderFactory factory = IdentityUtil.getSecuredDocumentBuilderFactory();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(byteArrayInputStream);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            t = (T) jaxbUnmarshaller.unmarshal(document);
        } catch (ParserConfigurationException | SAXException | IOException e) {
            log.error("Error while unmarshalling the XML.", e);
        }
    }
    return t;
}
 
Example 7
Source File: EntitlementUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * * This method provides a secured document builder which will secure XXE attacks.
 *
 * @param setIgnoreComments whether to set setIgnoringComments in DocumentBuilderFactory.
 * @return DocumentBuilder
 * @throws ParserConfigurationException
 */
private static DocumentBuilder getSecuredDocumentBuilder(boolean setIgnoreComments) throws
        ParserConfigurationException {

    DocumentBuilderFactory documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory();
    documentBuilderFactory.setIgnoringComments(setIgnoreComments);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    return documentBuilder;

}
 
Example 8
Source File: PolicyReader.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private PolicyReader(PolicyFinder policyFinder) {

        this.policyFinder = policyFinder;
        // create the factory
        DocumentBuilderFactory factory = IdentityUtil.getSecuredDocumentBuilderFactory();
        factory.setIgnoringComments(true);
        // now use the factory to create the document builder
        try {
            builder = factory.newDocumentBuilder();
            builder.setErrorHandler(this);
        } catch (ParserConfigurationException pce) {
            throw new IllegalArgumentException("Filed to setup repository: ");
        }
    }
 
Example 9
Source File: ApplicationManagementServiceImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Convert service provider object of service provider to xml formatted string
 *
 * @param serviceProvider service provider to be marshaled
 * @param tenantDomain    tenant domain
 * @return xml formatted string of the service provider
 * @throws IdentityApplicationManagementException Identity Application Management Exception
 */
private String marshalSP(ServiceProvider serviceProvider, String tenantDomain)
        throws IdentityApplicationManagementException {

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(ServiceProvider.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        DocumentBuilderFactory docBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory();
        Document document = docBuilderFactory.newDocumentBuilder().newDocument();
        marshaller.marshal(serviceProvider, document);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS,
                "AuthenticationScript inboundConfiguration");

        StringWriter stringBuilder = new StringWriter();
        StreamResult result = new StreamResult(stringBuilder);
        transformer.transform(new DOMSource(document), result);
        return stringBuilder.getBuffer().toString();
    } catch (JAXBException | ParserConfigurationException | TransformerException e) {
        throw new IdentityApplicationManagementException(String.format("Error in exporting Service Provider %s@%s",
                serviceProvider.getApplicationName(), tenantDomain), e);
    }
}
 
Example 10
Source File: PolicyEditorService.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Formats a given unformatted XML string
 *
 * @param xml
 * @return A CDATA wrapped, formatted XML String
 */
public String formatXML(String xml) {

    try {
        DocumentBuilder docBuilder;
        Document xmlDoc;

        // create the factory
        DocumentBuilderFactory docFactory = IdentityUtil.getSecuredDocumentBuilderFactory();
        docFactory.setIgnoringComments(true);

        // now use the factory to create the document builder
        docBuilder = docFactory.newDocumentBuilder();
        xmlDoc = docBuilder.parse(new ByteArrayInputStream(xml.getBytes(Charsets.UTF_8)));


        OutputFormat format = new OutputFormat(xmlDoc);
        format.setLineWidth(0);
        format.setIndenting(true);
        format.setIndent(2);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XMLSerializer serializer = new XMLSerializer(baos, format);
        serializer.serialize(xmlDoc);

        xml = baos.toString("UTF-8");

    } catch (ParserConfigurationException pce) {
        throw new IllegalArgumentException("Failed to parse the unformatted XML String. ", pce);
    } catch (Exception e) {
        log.error("Error occured while formtting the unformatted XML String. ", e);
    }

    return "<![CDATA[" + xml + "]]>";
}
 
Example 11
Source File: TenantDataManager.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieve latest active tenant domains list
 */
private static void refreshActiveTenantDomainsList() {

    try {
        String xmlString = getServiceResponse(serviceURL);

        if (StringUtils.isNotEmpty(xmlString)) {

            XPathFactory xpf = XPathFactory.newInstance();
            XPath xpath = xpf.newXPath();

            InputSource inputSource = new InputSource(new StringReader(xmlString));

            DocumentBuilderFactory factory = IdentityUtil.getSecuredDocumentBuilderFactory();

            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(inputSource);

            String xPathExpression = "/*[local-name() = '" + Constants.TenantConstants.RETRIEVE_TENANTS_RESPONSE
                    + "']/*[local-name() = '" +
                    Constants.TenantConstants.RETURN + "']";

            XPathExpression expr = xpath.compile(xPathExpression);
            NodeList nodeList = null;
            nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

            // Reset existing tenant domains list
            tenantDomainList.clear();

            // For each loop is not supported for NodeList
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    NodeList tenantData = element.getChildNodes();
                    boolean activeChecked = false;
                    boolean domainChecked = false;
                    boolean isActive = false;
                    String tenantDomain = null;

                    // For each loop is not supported for NodeList
                    for (int j = 0; j < tenantData.getLength(); j++) {
                        Node dataItem = tenantData.item(j);
                        String localName = dataItem.getLocalName();

                        if (Constants.TenantConstants.ACTIVE.equals(localName)) {
                            // Current element has domain status active or inactive
                            activeChecked = true;
                            if (Boolean.parseBoolean(dataItem.getTextContent())) {
                                isActive = true;
                            }
                        }

                        if (Constants.TenantConstants.TENANT_DOMAIN.equals(localName)) {
                            // Current element has domain name of the tenant
                            domainChecked = true;
                            tenantDomain = dataItem.getTextContent();
                        }

                        if (activeChecked && domainChecked) {
                            if (isActive) {
                                tenantDomainList.add(tenantDomain);

                                if (log.isDebugEnabled()) {
                                    log.debug(tenantDomain + " is active and added to the dropdown list");
                                }
                            } else {
                                if (log.isDebugEnabled()) {
                                    log.debug(tenantDomain + " is inactive and not added to the dropdown list");
                                }
                            }
                            break;
                        }
                    }
                }
            }
            // Sort the list of tenant domains alphabetically
            Collections.sort(tenantDomainList);
        }
    } catch (Exception e) {
        // Catching the general exception as if no tenants are available it should stop processing
        log.error("Retrieving list of active tenant domains failed. Ignore this if there are no tenants : ", e);
    }
}
 
Example 12
Source File: JSONRequestParser.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * This is to seperate JSON to attributes
 * @param jsonAttribute - the map of category string and the JSON Element
 * @param jsonCategory - the  main object category
 * @param categories - the set of categories
 * @throws RequestParseException
 * @throws UnknownIdentifierException
 */
private static void jsonAttributeSeperator(Map.Entry<String, JsonElement> jsonAttribute, JsonObject jsonCategory,
                                           Set<Attributes> categories) throws
        RequestParseException, UnknownIdentifierException {

    Node content = null;
    URI category = null;
    Set<Attribute> attributes = null;
    String id = null;

    if (EntitlementEndpointConstants.CATEGORY_DEFAULT.equals(jsonAttribute.getKey())) {
        if (jsonCategory.has(EntitlementEndpointConstants.CATEGORY_ID)) {
            category = stringCateogryToURI(jsonCategory
                    .get(EntitlementEndpointConstants.CATEGORY_ID)
                    .getAsString());
        }
    } else {
        if (category == null) {
            category = stringCateogryToURI(jsonAttribute.getKey());
        }
        if (jsonCategory.has(EntitlementEndpointConstants.ID)) {
            id = jsonCategory.get(EntitlementEndpointConstants.ID).getAsString();
        }
        if (jsonCategory.has(EntitlementEndpointConstants.CONTENT)) {
            DocumentBuilderFactory dbf;
            Document doc = null;

            String xmlContent = stringContentToXMLContent(jsonCategory
                    .get(EntitlementEndpointConstants.CONTENT)
                    .getAsString());
            dbf = IdentityUtil.getSecuredDocumentBuilderFactory();
            dbf.setNamespaceAware(true);

            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(xmlContent.getBytes())) {
                doc = dbf.newDocumentBuilder().parse(inputStream);
            } catch (Exception e) {
                throw new JsonParseException("DOM of request element can not be created from String.", e);
            }
            if (doc != null) {
                content = doc.getDocumentElement();
            }
        }

        // Add all category attributes
        if (jsonCategory.has(EntitlementEndpointConstants.ATTRIBUTE)) {
            if (jsonCategory.get(EntitlementEndpointConstants.ATTRIBUTE).isJsonArray()) {
                attributes = new HashSet<>();
                for (JsonElement jsonElement : jsonCategory.get(EntitlementEndpointConstants.ATTRIBUTE)
                        .getAsJsonArray()) {
                    attributes.add(jsonObjectToAttribute(jsonElement.getAsJsonObject()));
                }
            }
        }

    }
    //Build the Attributes object using above values
    Attributes attributesObj = new Attributes(category, content, attributes, id);
    categories.add(attributesObj);
}
 
Example 13
Source File: EntitlementEngine.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Evaluates the given XACML request and returns the ResponseCtx Response that the EntitlementEngine will
 * hand back to the PEP. PEP needs construct the XACML request before sending it to the
 * EntitlementEngine
 *
 * @param xacmlRequest XACML request as String
 * @return ResponseCtx response
 * @throws org.wso2.balana.ParsingException                          throws
 * @throws org.wso2.carbon.identity.entitlement.EntitlementException throws
 * @throws javax.xml.parsers.ParserConfigurationException            throws
 * @throws org.xml.sax.SAXException                                  throws
 * @throws java.io.IOException                                       throws
 */

public ResponseCtx evaluateReturnResponseCtx(String xacmlRequest) throws EntitlementException, ParsingException,
        ParserConfigurationException, SAXException, IOException {

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) {
        log.debug("XACML Request : " + xacmlRequest);
    }

    String xacmlResponse;
    ResponseCtx responseCtx;

    if ((xacmlResponse = (String) getFromCache(xacmlRequest, false)) != null) {
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
            log.debug("XACML Response : " + xacmlResponse);
        }

        DocumentBuilderFactory documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory();
        Element node = documentBuilderFactory.newDocumentBuilder().parse
                (new ByteArrayInputStream(xacmlResponse.getBytes())).getDocumentElement();


        return (ResponseCtx.getInstance(node));

    }

    Map<PIPExtension, Properties> extensions = EntitlementServiceComponent.getEntitlementConfig()
            .getExtensions();

    if (extensions != null && !extensions.isEmpty()) {
        PolicyRequestBuilder policyRequestBuilder = new PolicyRequestBuilder();
        Element xacmlRequestElement = policyRequestBuilder.getXacmlRequest(xacmlRequest);
        AbstractRequestCtx requestCtx = RequestCtxFactory.getFactory().
                getRequestCtx(xacmlRequestElement);
        Set<PIPExtension> pipExtensions = extensions.keySet();
        for (PIPExtension pipExtension : pipExtensions) {
            pipExtension.update(requestCtx);
        }
        responseCtx = pdp.evaluate(requestCtx);
    } else {
        responseCtx = pdp.evaluateReturnResponseCtx(xacmlRequest);
    }

    xacmlResponse = responseCtx.encode();

    addToCache(xacmlRequest, xacmlResponse, false);

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
        log.debug("XACML Response : " + xacmlResponse);
    }

    return responseCtx;

}
 
Example 14
Source File: InMemoryPersistenceManager.java    From carbon-identity-framework with Apache License 2.0 2 votes vote down vote up
/**
 * * This method provides a secured document builder which will secure XXE attacks.
 *
 * @return DocumentBuilder
 * @throws ParserConfigurationException
 */
private DocumentBuilder getSecuredDocumentBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    return documentBuilder;
}
 
Example 15
Source File: UserRegistrationService.java    From carbon-identity-framework with Apache License 2.0 2 votes vote down vote up
/**
 * * This method provides a secured document builder which will secure XXE attacks.
 *
 * @return DocumentBuilder
 * @throws ParserConfigurationException
 */
private DocumentBuilder getSecuredDocumentBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    return documentBuilder;
}