Example usage for java.io FilePermission FilePermission

List of usage examples for java.io FilePermission FilePermission

Introduction

In this page you can find the example usage for java.io FilePermission FilePermission.

Prototype


FilePermission(String path, int mask) 

Source Link

Document

Creates a new FilePermission object using an action mask.

Usage

From source file:Main.java

public static void main(String[] args) {
    AccessControlContext con = AccessController.getContext();

    System.setProperty("java.security.policy", "file:/C:/java.policy");

    SecurityManager sm = new Main();

    System.setSecurityManager(sm);

    sm.checkPermission(new FilePermission("test.txt", "read,write"), con);

    System.out.println("Allowed!");
}

From source file:com.thoughtworks.acceptance.SecurityManagerTest.java

protected void setUp() throws Exception {
    super.setUp();
    System.setSecurityManager(null);
    source = new CodeSource(new File("target").toURI().toURL(), (Certificate[]) null);

    sm = new DynamicSecurityManager();
    Policy policy = Policy.getPolicy();
    sm.setPermissions(source, policy.getPermissions(source));
    sm.addPermission(source, new RuntimePermission("setSecurityManager"));

    File mainClasses = new File(System.getProperty("user.dir"), "target/classes/-");
    File testClasses = new File(System.getProperty("user.dir"), "target/test-classes/-");
    String[] javaClassPath = StringUtils.split(System.getProperty("java.class.path"), File.pathSeparatorChar);
    File javaHome = new File(System.getProperty("java.home"), "-");

    // necessary permission start here
    sm.addPermission(source, new FilePermission(mainClasses.toString(), "read"));
    sm.addPermission(source, new FilePermission(testClasses.toString(), "read"));
    sm.addPermission(source, new FilePermission(javaHome.toString(), "read"));
    for (int i = 0; i < javaClassPath.length; ++i) {
        if (javaClassPath[i].endsWith(".jar")) {
            sm.addPermission(source, new FilePermission(javaClassPath[i], "read"));
        }//from   www .  j  a  va  2s.  com
    }
}

From source file:com.sshtools.common.ui.ResourceIcon.java

/**
 *
 *
 * @param imageName// w  ww  . ja  v  a  2  s  .c o  m
 */
protected void loadImage(String imageName) {
    Image image = null;
    URL url = cls.getResource(imageName);

    if (url != null) {
        log.debug(url.toString());
        image = Toolkit.getDefaultToolkit().getImage(url);
    } else {
        try {
            if (System.getSecurityManager() != null) {
                AccessController.checkPermission(new FilePermission(imageName, "read"));
            }

            image = Toolkit.getDefaultToolkit().getImage(imageName);
        } catch (AccessControlException ace) {
            log.error("Icon " + imageName + " could not be located as a "
                    + "resource, and the current security manager will not "
                    + "allow checking for a local file.");
        }
    }

    if (image != null) {
        this.setImage(image);
    }
}

From source file:com.sshtools.j2ssh.transport.AbstractKnownHostsKeyVerification.java

/**
 * <p>/*w w  w  . ja  v a2s.c om*/
 * Constructs a host key verification instance reading the specified
 * known_hosts file.
 * </p>
 *
 * @param knownhosts the path of the known_hosts file
 *
 * @throws InvalidHostFileException if the known_hosts file is invalid
 *
 * @since 0.2.0
 */
public AbstractKnownHostsKeyVerification(String knownhosts) throws InvalidHostFileException {
    InputStream in = null;

    try {
        //  If no host file is supplied, or there is not enough permission to load
        //  the file, then just create an empty list.
        if (knownhosts != null) {
            if (System.getSecurityManager() != null) {
                AccessController.checkPermission(new FilePermission(knownhosts, "read"));
            }

            //  Load the hosts file. Do not worry if fle doesnt exist, just disable
            //  save of
            File f = new File(knownhosts);

            if (f.exists()) {
                in = new FileInputStream(f);

                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line;

                while ((line = reader.readLine()) != null) {
                    StringTokenizer tokens = new StringTokenizer(line, " ");
                    String host = (String) tokens.nextElement();
                    String algorithm = (String) tokens.nextElement();
                    String key = (String) tokens.nextElement();

                    SshPublicKey pk = SshKeyPairFactory.decodePublicKey(Base64.decode(key));

                    /*if (host.indexOf(",") > -1) {
                       host = host.substring(0, host.indexOf(","));
                     }*/
                    putAllowedKey(host, pk);

                    //allowedHosts.put(host + "#" + pk.getAlgorithmName(), pk);
                }

                reader.close();

                hostFileWriteable = f.canWrite();
            } else {
                // Try to create the file and its parents if necersary
                f.getParentFile().mkdirs();

                if (f.createNewFile()) {
                    FileOutputStream out = new FileOutputStream(f);
                    out.write(toString().getBytes());
                    out.close();
                    hostFileWriteable = true;
                } else {
                    hostFileWriteable = false;
                }
            }

            if (!hostFileWriteable) {
                log.warn("Host file is not writeable.");
            }

            this.knownhosts = knownhosts;
        }
    } catch (AccessControlException ace) {
        hostFileWriteable = false;
        log.warn("Not enough permission to load a hosts file, so just creating an empty list");
    } catch (IOException ioe) {
        hostFileWriteable = false;
        log.info("Could not open or read " + knownhosts + ": " + ioe.getMessage());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:com.sshtools.common.hosts.AbstractHostKeyVerification.java

/**
 * Creates a new AbstractHostKeyVerification object.
 *
 * @param hostFileName//from   www.  ja  va 2  s .  c o m
 *
 * @throws InvalidHostFileException
 */
public AbstractHostKeyVerification(String hostFileName) throws InvalidHostFileException {
    InputStream in = null;

    try {
        //  If no host file is supplied, or there is not enough permission to load
        //  the file, then just create an empty list.
        if (hostFileName != null) {
            if (System.getSecurityManager() != null) {
                AccessController.checkPermission(new FilePermission(hostFileName, "read"));
            }

            //  Load the hosts file. Do not worry if fle doesnt exist, just disable
            //  save of
            File f = new File(hostFileName);

            if (f.exists()) {
                in = new FileInputStream(f);
                hostFile = hostFileName;

                SAXParserFactory saxFactory = SAXParserFactory.newInstance();
                SAXParser saxParser = saxFactory.newSAXParser();
                saxParser.parse(in, this);
                hostFileWriteable = f.canWrite();
            } else {
                // Try to create the file
                if (f.createNewFile()) {
                    FileOutputStream out = new FileOutputStream(f);
                    out.write(toString().getBytes());
                    out.close();
                    hostFileWriteable = true;
                } else {
                    hostFileWriteable = false;
                }
            }

            if (!hostFileWriteable) {
                log.warn("Host file is not writeable.");
            }
        }
    } catch (AccessControlException ace) {
        log.warn("Not enough permission to load a hosts file, so just creating an empty list");
    } catch (IOException ioe) {
        throw new InvalidHostFileException("Could not open or read " + hostFileName);
    } catch (SAXException sax) {
        throw new InvalidHostFileException("Failed XML parsing: " + sax.getMessage());
    } catch (ParserConfigurationException pce) {
        throw new InvalidHostFileException("Failed to initialize xml parser: " + pce.getMessage());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:com.sshtools.common.ui.SshToolsApplication.java

/**
 * Creates a new SshToolsApplication object.
 *
 * @param panelClass//from   w w  w.jav a2  s.  co m
 * @param defaultContainerClass
 */
public SshToolsApplication(Class panelClass, Class defaultContainerClass) {
    this.panelClass = panelClass;
    this.defaultContainerClass = defaultContainerClass;
    additionalOptionsTabs = new java.util.ArrayList();

    try {
        if (System.getSecurityManager() != null) {
            AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "write"));
        }

        File a = getApplicationPreferencesDirectory();

        if (a == null) {
            throw new AccessControlException("Application preferences directory not specified.");
        }

        InputStream in = null;
        MRUList mru = new MRUList();

        try {
            File f = new File(a, getApplicationName() + ".mru");

            if (f.exists()) {
                if (log.isDebugEnabled()) {
                    log.debug("Loading MRU from " + f.getAbsolutePath());
                }

                in = new FileInputStream(f);
                mru.reload(in);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("MRU file " + f.getAbsolutePath() + " doesn't exist, creating empty list");
                }
            }
        } catch (Exception e) {
            log.error("Could not load MRU list.", e);
        } finally {
            IOUtil.closeStream(in);
        }

        mruModel = new MRUListModel();
        mruModel.setMRUList(mru);
    } catch (AccessControlException ace) {
        log.error("Could not load MRU.", ace);
    }
}

From source file:com.jpeterson.littles3.bo.ResourcePermissionTest.java

/**
 * Test the <code>implies()</code> method.
 *///ww  w.  j  av  a  2  s.co m
public void test_implies() {
    ResourcePermission permission, another;
    CanonicalUser grantee;

    grantee = new CanonicalUser("id");
    permission = new ResourcePermission(grantee, ResourcePermission.ACTION_FULL_CONTROL);

    assertTrue("Should imply", permission.implies(permission));
    assertFalse("Should not imply", permission.implies(null));
    assertFalse("Should not imply", permission.implies(new FilePermission("/etc", "read")));

    another = new ResourcePermission(grantee, ResourcePermission.ACTION_READ);
    assertTrue("Should imply", permission.implies(another));
    another = new ResourcePermission(grantee, ResourcePermission.ACTION_WRITE);
    assertTrue("Should imply", permission.implies(another));
    another = new ResourcePermission(grantee, ResourcePermission.ACTION_READ_ACP);
    assertTrue("Should imply", permission.implies(another));
    another = new ResourcePermission(grantee, ResourcePermission.ACTION_WRITE_ACP);
    assertTrue("Should imply", permission.implies(another));
    another = new ResourcePermission(grantee, "read, write");
    assertTrue("Should imply", permission.implies(another));
    another = new ResourcePermission(grantee, "read, read_acp");
    assertTrue("Should imply", permission.implies(another));

    permission = new ResourcePermission(grantee, ResourcePermission.ACTION_READ);
    another = new ResourcePermission(grantee, ResourcePermission.ACTION_WRITE);
    assertFalse("Should not imply", permission.implies(another));

    permission = new ResourcePermission(grantee, ResourcePermission.ACTION_FULL_CONTROL);
    another = new ResourcePermission(new CanonicalUser("foo"), ResourcePermission.ACTION_FULL_CONTROL);
    assertFalse("Should not imply", permission.implies(another));

    permission = new ResourcePermission(AuthenticatedUsersGroup.getInstance(), "read, read_acp");
    another = new ResourcePermission(grantee, ResourcePermission.ACTION_READ);
    assertTrue("Should imply", permission.implies(another));
    another = new ResourcePermission(grantee, ResourcePermission.ACTION_WRITE);
    assertFalse("Should not imply", permission.implies(another));

    permission = new ResourcePermission(AuthenticatedUsersGroup.getInstance(), "read, read_acp");
    another = new ResourcePermission(new CanonicalUser(CanonicalUser.ID_ANONYMOUS),
            ResourcePermission.ACTION_READ);
    assertFalse("Should not imply", permission.implies(another));

    permission = new ResourcePermission(AllUsersGroup.getInstance(), "read");
    another = new ResourcePermission(grantee, ResourcePermission.ACTION_READ);
    assertTrue("Should imply", permission.implies(another));
    another = new ResourcePermission(grantee, ResourcePermission.ACTION_WRITE);
    assertFalse("Should not imply", permission.implies(another));

    permission = new ResourcePermission(AllUsersGroup.getInstance(), "read");
    another = new ResourcePermission(new CanonicalUser(CanonicalUser.ID_ANONYMOUS),
            ResourcePermission.ACTION_READ);
    assertTrue("Should imply", permission.implies(another));
    another = new ResourcePermission(new CanonicalUser(CanonicalUser.ID_ANONYMOUS),
            ResourcePermission.ACTION_WRITE);
    assertFalse("Should not imply", permission.implies(another));
}

From source file:co.cask.cdap.app.deploy.SandboxJVM.java

/**
 * Main class within the object./*from  ww w  .ja  v a 2 s.  c o m*/
 *
 * @param args specified on command line.
 * @return 0 if successfull; otherwise non-zero.
 */
public int doMain(String[] args) {
    String jarFilename;
    File outputFile;
    String locationFactory;
    String id;
    LocationFactory lf;

    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    options.addOption("i", "id", true, "Account ID");
    options.addOption("j", "jar", true, "Application JAR");
    options.addOption("f", "locfactory", true, "Location Factory (LOCAL or DISTRIBUTED)");
    options.addOption("o", "output", true, "Output");

    // Check all the options of command line
    try {
        CommandLine line = parser.parse(options, args);
        if (!line.hasOption("jar")) {
            LOG.error("Application JAR not specified.");
            return -1;
        }
        if (!line.hasOption("output")) {
            LOG.error("Output file not specified.");
            return -1;
        }
        if (!line.hasOption("id")) {
            LOG.error("Account id not specified.");
            return -1;
        }
        if (!line.hasOption("locfactory")) {
            LOG.error("Location factory not specified.");
            return -1;
        }

        jarFilename = line.getOptionValue("jar");
        outputFile = new File(line.getOptionValue("output"));
        id = line.getOptionValue("id");
        locationFactory = line.getOptionValue("locfactory");
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("SandboxJVM", options);
        return -1;
    }

    // Load the JAR using the JAR class load and load the manifest file.
    File unpackedJarDir = Files.createTempDir();

    try {
        Application app;
        try {
            if ("LOCAL".equals(locationFactory)) {
                lf = new LocalLocationFactory();
            } else if ("DISTRIBUTED".equals(locationFactory)) {
                lf = new HDFSLocationFactory(new Configuration());
            } else {
                LOG.error("Unknown location factory specified");
                return -1;
            }

            Program archive = Programs.createWithUnpack(lf.create(jarFilename), unpackedJarDir);
            Object appMain = archive.getMainClass().newInstance();
            if (!(appMain instanceof Application)) {
                LOG.error(String.format("Application main class is of invalid type: %s",
                        appMain.getClass().getName()));
                return -1;
            }

            app = (Application) appMain;

        } catch (Exception e) {
            LOG.error(e.getMessage());
            return -1;
        }

        // Now, we are ready to call configure on application.
        // Setup security manager, this setting allows only output file to be written.
        // Nothing else can be done from here on other than creating that file.
        ApplicationSecurity.builder().add(new FilePermission(outputFile.getAbsolutePath(), "write")).apply();

        // Now, we call configure, which returns application specification.
        DefaultAppConfigurer configurer = new DefaultAppConfigurer(app);
        app.configure(configurer, new ApplicationContext());
        ApplicationSpecification specification = configurer.createApplicationSpec();

        // Convert the specification to JSON.
        // We write the Application specification to output file in JSON format.
        try {
            Writer writer = Files.newWriter(outputFile, Charsets.UTF_8);
            try {
                // TODO: The SchemaGenerator should be injected.
                ApplicationSpecificationAdapter.create(new ReflectionSchemaGenerator()).toJson(specification,
                        writer);
            } finally {
                writer.close();
            }
        } catch (IOException e) {
            LOG.error("Error writing to file {}. {}", outputFile, e.getMessage());
            return -1;
        }
    } finally {
        try {
            FileUtils.deleteDirectory(unpackedJarDir);
        } catch (IOException e) {
            LOG.warn("Error deleting temp unpacked jar directory: {}", unpackedJarDir.getAbsolutePath(), e);
        }
    }

    return 0;
}

From source file:com.stratuscom.harvester.deployer.StarterServiceDeployer.java

public void setupLiaisonConfiguration(ApplicationEnvironment env) throws ConfigurationException {
    /*/*w w w.ja v  a  2s.c om*/
     Setup the liaison configuration.
     */
    ClassLoader originalContextCl = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(env.getClassLoader());
        File workingDir = null;
        if (env.getServiceArchive() != null) {
            /* This variable, and the method we're calling on VirtualFileSystemConfiguration,
            is named in an unfortunate manner for 
            historical reasons.  What we're really doing here is telling the 
            VirtualFileSystemConfiguration where to read its configuration 
            file from.  Iternally to VFSConfig, it's called the "root" directory.
            It has nothing to do with the "working" directory where the service
            should be allowed to write its own data.
            */
            workingDir = new File(env.getServiceArchive().getURL().toURI());
        } else {
            workingDir = new File(env.getServiceArchive().getURL().toURI());

        }

        grantPermissions(env.getClassLoader(),
                new Permission[] { new FilePermission(workingDir.getAbsolutePath(), Strings.READ) });
        Utils.logClassLoaderHierarchy(log, Level.FINE, this.getClass());
        String configName = VirtualFileSystemConfiguration.class.getName();
        invokeStatic(env.getClassLoader(), configName, Strings.SET_WORKING_DIRECTORY, workingDir);
        /*
         Setup the "special" variables in the configuration.
         */
        ASTconfiguration configurationNode = (ASTconfiguration) configNode
                .search(new Class[] { ASTconfig.class, ASTconfiguration.class }).get(0);
        for (int i = 0; i < configurationNode.jjtGetNumChildren(); i++) {
            ASTconfigEntry cfgEntryNode = (ASTconfigEntry) configurationNode.jjtGetChild(i);
            String varName = cfgEntryNode.jjtGetChild(0).toString();
            String contextVarName = cfgEntryNode.jjtGetChild(1).toString();
            Object contextValue = context.get(contextVarName);
            if (contextValue != null) {
                invokeStatic(env.getClassLoader(), configName, Strings.PUT_SPECIAL_ENTRY,
                        new Class[] { String.class, Object.class }, Strings.DOLLAR + varName, contextValue);
            } else {
                log.log(Level.WARNING, MessageNames.MISSING_SPECIAL_VALUE,
                        new Object[] { getConfig(), varName, contextVarName });
            }
        }

        /* 
        One extra "special" variable is the File that gives the working directory.
        */
        invokeStatic(env.getClassLoader(), configName, Strings.PUT_SPECIAL_ENTRY,
                new Class[] { String.class, Object.class }, Strings.DOLLAR + Strings.WORKING_DIRECTORY,
                env.getWorkingDirectory());
        /* Install the Executor. */
        log.log(Level.INFO, MessageNames.EXECUTOR_NAME_IS,
                new Object[] { Strings.DOLLAR + Strings.EXECUTOR_NAME });
        invokeStatic(env.getClassLoader(), configName, Strings.PUT_SPECIAL_ENTRY,
                new Class[] { String.class, Object.class }, Strings.DOLLAR + Strings.EXECUTOR_NAME,
                env.getWorkingContext().getScheduledExecutorService());

    } catch (Exception ex) {
        log.log(Level.WARNING, MessageNames.EXCEPTION_THROWN, Utils.stackTrace(ex));
        throw new ConfigurationException(ex, MessageNames.STARTER_SERVICE_DEPLOYER_FAILED_INIT);
    } finally {
        Thread.currentThread().setContextClassLoader(originalContextCl);
    }
}

From source file:com.sshtools.appframework.ui.SshToolsApplication.java

@SuppressWarnings("serial")
private void loadMRU() {
    try {/*from w w w .j av a 2s  .  co m*/
        if (System.getSecurityManager() != null) {
            AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "write"));
        }
        File a = getApplicationPreferencesDirectory();
        if (a == null) {
            throw new AccessControlException("Application preferences directory not specified.");
        }
        InputStream in = null;
        MRUList mru = new MRUList();
        try {
            File f = new File(a, getApplicationName() + ".mru");
            if (f.exists()) {
                in = new FileInputStream(f);
                mru.reload(in);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtil.closeStream(in);
        }
        mruModel = new MRUListModel() {
            @Override
            public void add(File f) {
                super.add(f);
                saveMRU(SshToolsApplication.this);
            }

            @Override
            public void setMRUList(MRUList mru) {
                super.setMRUList(mru);
            }
        };
        mruModel.setMRUList(mru);
    } catch (AccessControlException ace) {
        ace.printStackTrace();
    }
}