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

📄 permistestbench.java

📁 一个完整的XACML工程,学习XACML技术的好例子!
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/*
* 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.
*/
package issrg.test.ptb;

import issrg.pba.*;
import issrg.pba.rbac.*;
import issrg.pba.rbac.x509.RepositoryACPolicyFinder;

import java.util.ArrayList;
import java.util.Hashtable;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.math.BigInteger;
import java.net.URL;
import java.io.File;

/**
 * This is the class for the Permis Test Bench Program. This application can be used for two purposes:
 * <p>
 * <nl>
 *  <li> It can generate authorisation decisions based on the following inputs:
 *     <ul>
 *     <li> Name of the file containing the information about the identity and attribute
 *       certificates to be used during the decision process
 *     <li> Name of the file containing the set of requests (user, target, action, and arguments)
 *     </ul>
 *  <li> It is able to compare two different authorisation decision files, previously generated,
 *     in order to check whether there are differences between the decision obtained for the
 *     same input request.
 * </nl>
 * @author O Canovas
 * @author O Otenko
 * @version 0.1
 */

public class PermisTestBench {
    protected static java.io.PrintStream out = System.out;
    protected static java.io.PrintStream err = System.err;

    protected String SOA = ""; 	//Distinguished name of the SOA
	protected String oID = "";  //OID of the policy
    protected PBAAPI pbaApi = null; //Reference to the PBA API
    protected PTBClock clock;
    protected PermisAction permisAction; //Current Action being requested
    protected PermisTarget permisTarget; //Current Target being requested
    protected String userDN;  //Distinguished name of the current user
    protected String rqNumber;  //Number of requests already processed
    protected issrg.pba.rbac.SignatureVerifier sv;  //Signature Verifier to be used
	protected issrg.utils.repository.VirtualRepository vr; //Virtual Repository

	public static void main(String [] args){
		System.setProperty("line.separator", "\r\n");
          try{

        PermisTestBench bench = new PermisTestBench();

		try{
                    if (args.length >= 5) {
                        java.io.PrintStream ps = new java.io.PrintStream(new java.io.FileOutputStream(args[args.length-1]));
                        System.setOut(ps);
                        System.setErr(ps);
                    }

			if (args.length < 5) {
                printUsage();  // Both generation and check need at least 4 arguments
			}
            // We check whether the user wants to generate a decision file
            // (the first application's argument contains the type of operation to perform)
            else if (args[0].intern() == "-generate") {
                boolean check;
                // We check whether the user is interested in verifying digital signatures
                // attached to the identity and attribute certificates (5th argument)
                if ((args.length == 6) && (args[4]).intern() == "-ignore-signatures")
                    check = false;
                else check = true;
                // Now, it's time to load the certificates specified by the repository file
                // (the name of that file must be the 2nd argument of this application)
                if (!bench.loadRepositoryFile(args[1],check))
                    return;  //File format is not valid!
                // Once we know the SOA, the policy's OID, and the certificates, we can initialise
                // the PBA API
                if (!bench.initialisePBAAPI())
                    return;  //Problem during initialisation
                // Finally, it's time to process the requests contained in the file specified
                // by the 3rd argument and to generate the file containing the decisions (4th arg)
                bench.loadRequestsAndGenerateDecisions(args[2],args[3]);
			}
            // Second option: the user wants to find out differences between two decision files
            // specified as the 2nd and 3rd arguments, and to store those differences in the file
            // specified by the 4th argument.
            else if (args[0].intern() == "-check") {
                bench.checkDecisionFiles(args[1],args[2],args[3]);
            }
            else {
                // The first argument must be "-generate" or "-check"
                printUsage();
            }

		}catch (Throwable th){
			System.out.println("Failed to initialise: "+th.getMessage());
			th.printStackTrace();
		}
          }finally{
            System.setOut(out);
            System.setErr(err);
          }
	}

    /**
     * Prints how to use this application
     *
     */
    public static void printUsage()
    {
        System.out.println("Usage:");
        System.out.println("  1. To generate an output file containing decisions");
        System.out.println("    PermisTestBench -generate <repository_spec_file> <rq_spec_file> <decision_file> [-ignore-signatures] <stdio and stderr redirect_file>");
        System.out.println("  2. To compare two decision files containing decisions");
        System.out.println("    PermisTestBench -check <decision_file1> <decision_file2> <output_diff_file> <stdio and stderr redirect_file>");
    }


    /**
     * Constructs a Permis Test Bench. It has no parameters, and
     * its main function is to initialise the Virtual Repository
     */
	public PermisTestBench(){
           vr = new issrg.utils.repository.VirtualRepository();
           try{
                CustomisePERMIS.setSystemClock("issrg.test.ptb.PTBClock");
                clock = (PTBClock)CustomisePERMIS.getSystemClock();
           }catch(Exception e){
              // shouldn't have happened
              e.printStackTrace();
           }
	}

    /**
     * Loads attribute certificates in order to insert them into the
     * virtual repository
     *
     * @param vr is the virtual repository
     * @param filename is the name of the file containing the attribute certificate
     * @return true if the certificate was successfully inserted
     */
    protected boolean loadAC(issrg.utils.repository.VirtualRepository vr, String filename){
        try{
            java.io.InputStream io = new java.io.FileInputStream(filename);
            byte [] ac = new byte [io.available()];

            io.read(ac);

            issrg.ac.AttributeCertificate acd = issrg.ac.AttributeCertificate.guessEncoding(ac);

            vr.populate(issrg.ac.Util.generalNamesToString(acd.getACInfo().getHolder().getEntityName()).toUpperCase(),
                CustomisePERMIS.getAttributeCertificateAttribute(),
                ac);
            return true;
        } catch (Throwable th){
            System.out.println("Failed to load AC from ["+filename+"]");
            th.printStackTrace();
            return false;
        }
    }

    /**
     * Reads the repository specification file. That file must have the
     * following format (the number of entries, NOE, specifies the minimun and maximun number):
     * <p>
     * <ul>
     *   <li> <code>SOA_DN="distinguished name of the SOA"; NOE [1,1]</code>
     *   <li> <code>POLICY_OID="OID of the policy to enforce"; NOE [1,1]</code>
     *   <li> <code>CA="name of the file containing the identity certificate of the CA"; NOE [1,1]</code>
     *   <li> <code>SOA_CERT="name of the file containing the identity certificate of a SOA"; NOE [1,N]</code>
     *   <li> <code>POLICY_AC="name of the file containing the AC including the XML policy"; NOE [1,1]</code>
     *   <li> <code>AC="name of the file containing an AC to be stored"; NOE [0,N]</code>
     *   <li> <code>CURRENT_TIME="YYYY-MM-DD HH:MM:SS"; NOE [0,1]</code>
     * </ul>
     * <p>
     * If a line starts with #, it will be considered as a comment (it is ignored).
     *
     * <p>
     * Moreover, this method also initialises the SignatureVerifier implementation to be used
     * during the decision process.
     *
     * @param filename is the name of the file specifying the repository
     * @param check indicates whether the digital signatures will be verified
     * @return true if the <code>AttributeRepository</code> and the <code>SignatureVerifier</code> were initialised
     */
    public boolean loadRepositoryFile(String filename, boolean check) {
        try {
            java.io.BufferedReader in = new java.io.BufferedReader(new java.io.FileReader(filename));
            String s; //String containing the value of a parameter
            String varName = null; //String contining the name of the parameter
            String[] varValue = null; //Array of strings for the loadVarValue method
            PTBSignatureVerifier ptbSV = null; //Instance of the Permis Test Bench Sugnature Verifier

            // If "-ignore-signatures" was selected, then we are going to use the SamplePKI
            if (!check) sv = new SamplePKI();
            else {
                // Otherwise, we use a customised Signature Verifier built for the PTB
                sv = new PTBSignatureVerifier();
                ptbSV = (PTBSignatureVerifier) sv;
            }

            while ((varValue = loadVarValue(in))!=null){
                s = varValue[1];
                varName = varValue[0];

                if (varName == "SOA_DN"){
                    SOA = s;
                }else
                if (varName == "POLICY_OID"){
                    oID = s;
                }else
                if (varName == "CA") {
                    if (check)
                        if (!ptbSV.setCACertificate(s)) return false;
                } else
                if (varName == "SOA_CERT"){
                    if (check)
                        if (!ptbSV.addSOACertificate(s)) return false;
                }else
                if (varName == "POLICY_AC"){
                    loadAC(vr, s);
                }else
                if (varName == "CURRENT_TIME"){
                    clock.setTime(s);
                }else
                if (varName == "AC"){
                    loadAC(vr, s);
                }else
                    System.out.println("Unrecognised line; ignored: "+varName+"="+s);
            }
            return true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Reads (attribute,value) pairs from a buffered reader. This method
     * processes each line of the buffered reader looking for the <code>PARAMETER=VALUE</code> pattern.
     * Once that pattern is found, it returns an array of Strings containing the name of the
     * parameter in the first element and the value in the second element. On the other hand,
     * when the end of the buffered reader is reached, it returns <code>null</code>.
     *
     * @param in is the buffered reader
     * @return String[2]: <code>String[0]</code> is the name of the parameter;
     * <code>String[1]</code> is the value; <code>null if EOF</code>
     *
     */
    protected String[] loadVarValue(BufferedReader in) {
        String s = "";

⌨️ 快捷键说明

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