⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xacmlpdp.java

📁 一个完整的XACML工程,学习XACML技术的好例子!
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
* Copyright (c) 2006, University of Kent
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without 
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this 
* list of conditions and the following disclaimer.
* 
* Redistributions in binary form must reproduce the above copyright notice, 
* this list of conditions and the following disclaimer in the documentation 
* and/or other materials provided with the distribution. 
*
* 1. Neither the name of the University of Kent nor the names of its 
* contributors may be used to endorse or promote products derived from this 
* software without specific prior written permission. 
*
* 2. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS  
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
* PURPOSE ARE DISCLAIMED. 
*
* 3. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
* POSSIBILITY OF SUCH DAMAGE.
*
* 4. YOU AGREE THAT THE EXCLUSIONS IN PARAGRAPHS 2 AND 3 ABOVE ARE REASONABLE
* IN THE CIRCUMSTANCES.  IN PARTICULAR, YOU ACKNOWLEDGE (1) THAT THIS
* SOFTWARE HAS BEEN MADE AVAILABLE TO YOU FREE OF CHARGE, (2) THAT THIS
* SOFTWARE IS NOT "PRODUCT" QUALITY, BUT HAS BEEN PRODUCED BY A RESEARCH
* GROUP WHO DESIRE TO MAKE THIS SOFTWARE FREELY AVAILABLE TO PEOPLE WHO WISH
* TO USE IT, AND (3) THAT BECAUSE THIS SOFTWARE IS NOT OF "PRODUCT" QUALITY
* IT IS INEVITABLE THAT THERE WILL BE BUGS AND ERRORS, AND POSSIBLY MORE
* SERIOUS FAULTS, IN THIS SOFTWARE.
*
* 5. This license is governed, except to the extent that local laws
* necessarily apply, by the laws of England and Wales.
*/
/*
 * NewClass.java
 *
 * Created on 07 November 2006, 17:14
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package uk.ac.kent.dpa.custom.pdp;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.globus.wsrf.ResourceContext;
import org.globus.wsrf.ResourceContextException;
import org.globus.wsrf.security.authorization.PDP;
import org.globus.wsrf.security.authorization.PDPConfig;
import org.globus.wsrf.impl.security.util.AuthUtil;
import org.globus.wsrf.impl.security.authorization.exceptions.AuthorizationException;
import org.globus.wsrf.impl.security.authorization.exceptions.InitializeException;
import org.globus.wsrf.impl.security.authorization.exceptions.InvalidPolicyException;
import org.w3c.dom.*;

import javax.security.auth.Subject;
import javax.xml.rpc.handler.MessageContext;
import javax.xml.parsers.*;
import javax.xml.namespace.QName;
import uk.ac.kent.dpa.custom.authz.util.AuthzException;
import uk.ac.kent.dpa.custom.authz.util.XMLParser;

import uk.ac.kent.dpa.obligation.engine.BasicDom;

import java.security.Principal;
import java.util.*;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.xacml.ConfigurationStore;
import com.sun.xacml.Indenter;
import com.sun.xacml.ParsingException;
import com.sun.xacml.UnknownIdentifierException;
import com.sun.xacml.attr.AttributeFactory;
import com.sun.xacml.attr.AttributeValue;
import com.sun.xacml.attr.StringAttribute;
import com.sun.xacml.attr.IntegerAttribute;
import com.sun.xacml.attr.DoubleAttribute;

import com.sun.xacml.cond.FunctionFactory;
import com.sun.xacml.cond.FunctionFactoryProxy;
import com.sun.xacml.cond.StandardFunctionFactory;

import com.sun.xacml.ctx.RequestCtx;
import com.sun.xacml.ctx.ResponseCtx;
import com.sun.xacml.ctx.Attribute;

import com.sun.xacml.finder.AttributeFinder;
import com.sun.xacml.finder.PolicyFinder;

import com.sun.xacml.finder.impl.CurrentEnvModule;
import com.sun.xacml.finder.impl.FilePolicyModule;
import com.sun.xacml.finder.impl.SelectorModule;
import com.sun.xacml.simple.*;

import java.io.FileInputStream;
import java.io.IOException;

import issrg.web.service.EncodeXML;
/**
 *
 * @author ls97
 */
public class XacmlPDP implements PDP {
    
    static Log logger = LogFactory.getLog(XacmlPDP.class.getName());
    private com.sun.xacml.PDP[] xacmlPDP = null; 
    private String[] files = null;
    private Element[] policies = null;
    private Element response = null;
    /** Creates a new instance of NewClass */
    public XacmlPDP() {
    }
    
    public void initialize(PDPConfig config, String name, String id) throws InitializeException {
        logger.info("to construct XACML PDP with the policies");
        String policy = (String)config.getProperty(name,"customConfig");
        StringTokenizer tokenizer = new StringTokenizer(policy);
        this.files = new String[tokenizer.countTokens()];
        int c = 0;
        while (tokenizer.hasMoreTokens()) {
            String op = tokenizer.nextToken();
            this.files[c]= op.trim();
            logger.debug(files[c]);
            c++;
        }
        try {
            SimplePDP[] pdp = new SimplePDP[files.length];
            this.xacmlPDP = new com.sun.xacml.PDP[files.length];
            String[] pf = new String[1];
            for (int i=0; i<files.length; i++) {
                pf[0]=files[i];
                pdp[i] = new SimplePDP(pf);
                this.xacmlPDP[i]=pdp[i].getPDP();
            }
            logger.info("done!");
        } catch (Exception e) {
            throw new InitializeException("failed to construct an XACML PDP : "+e);
        }
    }

    public boolean isPermitted(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException {
        logger.info("the XACML PDP is called");
        Element requestCtx = (Element)context.getProperty("request.context");
        HashSet subjects = new HashSet(); 
	HashSet resources = new HashSet();
	HashSet actions = new HashSet();
	HashSet environment = new HashSet();
        HashSet attributes = new HashSet();
        if (requestCtx!=null) {
            NodeList list = requestCtx.getElementsByTagName("Subject");
            subjects = this.getSubject(list);
            list = requestCtx.getElementsByTagName("Resource");
            resources = this.getResource(list);
            list = requestCtx.getElementsByTagName("Action");
            actions = this.getAction(list);
            list = requestCtx.getElementsByTagName("Environment");
            environment = this.getEnvironment(list);
            try {
                if (subjects.isEmpty()) {
                    logger.debug("to get default subject attributes");
                    String subjectStr = AuthUtil.getIdentity(peerSubject);	
                    Attribute subjectAttribute = createAttribute
                                                ("urn:oasis:names:tc:xacml:1.0:subject:subject-id",
                                                "http://www.w3.org/2001/XMLSchema#string",	    
                                                subjectStr);
                    attributes.add(subjectAttribute);
                }
                com.sun.xacml.ctx.Subject subject = new com.sun.xacml.ctx.Subject(attributes);
                subjects.add(subject);
                if (resources.isEmpty()) {
                    logger.debug("to get default resource attributes");
                    Attribute resourceAttribute = createAttribute
                                                ("urn:oasis:names:tc:xacml:1.0:resource:resource-id",
                                                 "http://www.w3.org/2001/XMLSchema#string",	    
                                                 "Service");       
                    resources.add(resourceAttribute);
                }
                if (actions.isEmpty()) {
                    logger.debug("to get default action attributes");
                    Attribute actionAttribute = createAttribute
                                                ("urn:oasis:names:tc:xacml:1.0:action:action-id",
                                                 "http://www.w3.org/2001/XMLSchema#string",	    
                                                 operation);	
                    actions.add(actionAttribute);
                }
                if (environment.isEmpty()) {
                    logger.debug("to get default environment attributes");
                    environment.addAll(peerSubject.getPublicCredentials(Attribute.class));
                }
                RequestCtx request = new RequestCtx(subjects, resources, actions, environment);
                java.io.ByteArrayOutputStream byteStream = null;
                byteStream = new java.io.ByteArrayOutputStream();
                request.encode(byteStream, new com.sun.xacml.Indenter());
                XMLParser parser = new XMLParser(byteStream.toString());
                logger.debug(new EncodeXML().encode(parser.getXmlElement(),0));
                ResponseCtx res = null;
                for (int i=0; i<this.files.length; i++) {
                    logger.debug("to test "+i+1+" policy");
                    res = this.xacmlPDP[i].evaluate(request);
                    byteStream = new java.io.ByteArrayOutputStream();
                    res.encode(byteStream, new com.sun.xacml.Indenter());
                    parser = new XMLParser(byteStream.toString());
                    String result = this.getDecision(res);
                    this.response = parser.getXmlElement();
                    logger.debug(new EncodeXML().encode(this.response,0));
                    if (result.equals("Permit")) return true;
                }
                return false;
            } catch (Exception ae) {
                logger.debug("failed to make an authz decision:"+ae);
                return false;
            }
        } else {
            try {
                ResponseCtx res = this.evaluate(peerSubject,operation.getLocalPart());
                java.io.ByteArrayOutputStream byteStream = null;
                byteStream = new java.io.ByteArrayOutputStream();
                res.encode(byteStream, new com.sun.xacml.Indenter());
                XMLParser parser = new XMLParser(byteStream.toString());
                String result = this.getDecision(res);
                this.response = parser.getXmlElement();
                if (result.equals("Permit")) return true;
                else return false;
            } catch (Exception ae) {
                logger.debug("failed to convert XACML ResonseCtx to XML");
                return false;
            }
        }
    }
    
    private HashSet getAttributes(NodeList list) throws AuthorizationException {
        HashSet attributes = new HashSet();
        for (int i=0; i<list.getLength(); i++) {
            //get domain node (Subject, resource, Action or Environment
            Node node = list.item(i);
            if (Text.class.isAssignableFrom(node.getClass())) continue;
            NodeList list0 = node.getChildNodes();
            for (int k=0; k<list0.getLength(); k++) {
                //get Attribute node
                Node node0 = list0.item(k);
                if (Text.class.isAssignableFrom(node0.getClass())) continue;
                if (node0.getNodeName().equals("Attribute")) {
                    Element ele = (Element)node0;
                    String id = ele.getAttribute("AttributeId");
                    String type = ele.getAttribute("DataType");
                    NodeList list1 = node0.getChildNodes();
                    for (int j=0; j<list1.getLength(); j++) {
                        //get AttributeValue node
                        Node node1 = list1.item(j);
                        if (Text.class.isAssignableFrom(node1.getClass())) continue;
                        if (!node1.getNodeName().equals("AttributeValue")) continue;
                        NodeList list2 = node1.getChildNodes();
                        if (list2.getLength()!=1) continue;
                        Node node2 = list2.item(0);
                        if (!Text.class.isAssignableFrom(node2.getClass())) continue;                        
                        String value = node2.getNodeValue();
                        value = value.trim();
                        try {
                            Attribute subjectAttribute = createAttribute(id,type,value);
                            attributes.add(subjectAttribute);
                        } catch (Exception e) {
                            throw new AuthorizationException("failed to create XACML Subject");

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -