Example usage for java.lang SecurityManager checkPermission

List of usage examples for java.lang SecurityManager checkPermission

Introduction

In this page you can find the example usage for java.lang SecurityManager checkPermission.

Prototype

public void checkPermission(Permission perm) 

Source Link

Document

Throws a SecurityException if the requested access, specified by the given permission, is not permitted based on the security policy currently in effect.

Usage

From source file:Main.java

public static void main(String[] args) {
    System.setProperty("java.security.policy", "file:/C:/java.policy");

    SecurityManager sm = new Main();

    System.setSecurityManager(sm);

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

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

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        FilePermission fp = new FilePermission("c:\\autoexec.bat", "read");
        sm.checkPermission(fp);
    }//from  w  ww . j  av  a  2  s . co m

    if (sm != null) {
        AWTPermission ap = new AWTPermission("accessClipboard");
        sm.checkPermission(ap);
    }
    System.out.println("Has AWTPermission to access AWT Clipboard");

}

From source file:SecretWordPermission.java

public String getWord() {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        security.checkPermission(new SecretWordPermission("AccessPermission"));
    }/*from w  w w.j  a  va2 s .c  o m*/
    return "Secret";
}

From source file:com.scoredev.scores.HighScore.java

/**
 * get the high score. return -1 if it hasn't been set.
 *
 *///from www  . j a v  a 2  s .  c o m
public int getHighScore() throws IOException, ClassNotFoundException {
    //check permission first
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new HighScorePermission(gameName));
    }

    Integer score = null;

    // need a doPrivileged block to manipulate the file
    try {
        score = (Integer) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws IOException, ClassNotFoundException {
                Hashtable scores = null;
                // try to open the existing file. Should have a locking
                // protocol (could use File.createNewFile).
                FileInputStream fis = new FileInputStream(highScoreFile);
                ObjectInputStream ois = new ObjectInputStream(fis);
                scores = (Hashtable) ois.readObject();

                // get the high score out
                return scores.get(gameName);
            }
        });
    } catch (PrivilegedActionException pae) {
        Exception e = pae.getException();
        if (e instanceof IOException)
            throw (IOException) e;
        else
            throw (ClassNotFoundException) e;
    }
    if (score == null)
        return -1;
    else
        return score.intValue();
}

From source file:com.scoredev.scores.HighScore.java

public void setHighScore(final int score) throws IOException {
    //check permission first
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new HighScorePermission(gameName));
    }/*w  w w  .  j  av a 2  s . co  m*/

    // need a doPrivileged block to manipulate the file
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws IOException {
                Hashtable scores = null;
                // try to open the existing file. Should have a locking
                // protocol (could use File.createNewFile).
                try {
                    FileInputStream fis = new FileInputStream(highScoreFile);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    scores = (Hashtable) ois.readObject();
                } catch (Exception e) {
                    // ignore, try and create new file
                }

                // if scores is null, create a new hashtable
                if (scores == null)
                    scores = new Hashtable(13);

                // update the score and save out the new high score
                scores.put(gameName, new Integer(score));
                FileOutputStream fos = new FileOutputStream(highScoreFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(scores);
                oos.close();
                return null;
            }
        });
    } catch (PrivilegedActionException pae) {
        throw (IOException) pae.getException();
    }
}

From source file:io.fabric8.elasticsearch.plugin.auth.OpenShiftTokenAuthentication.java

private Collection<String> retrieveBackendRoles(OpenshiftRequestContext context) {
    List<String> roles = new ArrayList<>();
    if (PluginServiceFactory.isReady()) {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new SpecialPermission());
        }//from  ww  w .j  av  a  2 s.  c om
        OpenshiftAPIService apiService = PluginServiceFactory.getApiService();
        for (Map.Entry<String, Settings> sar : sars.entrySet()) {
            boolean allowed = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {

                @Override
                public Boolean run() {
                    try {
                        Settings params = sar.getValue();
                        return apiService.localSubjectAccessReview(context.getToken(), params.get("namespace"),
                                params.get("verb"), params.get("resource"), params.get("resourceAPIGroup"),
                                ArrayUtils.EMPTY_STRING_ARRAY);
                    } catch (Exception e) {
                        LOGGER.error("Exception executing LSAR", e);
                    }
                    return false;
                }

            });
            if (allowed) {
                roles.add(sar.getKey());
            }
        }
    }
    return roles;
}

From source file:com.petalmd.armor.service.ArmorService.java

@Inject
public ArmorService(final Settings settings, final RestController restController, final Client client,
        final Authorizator authorizator, final AuthenticationBackend authenticationBackend,
        final HTTPAuthenticator httpAuthenticator, final SessionStore sessionStore,
        final AuditListener auditListener, final SearchService searchService) {
    super(settings);
    this.restController = restController;
    this.client = client;
    this.settings = settings;
    //securityConfigurationIndex = settings
    //        .get(ConfigConstants.ARMOR_CONFIG_INDEX_NAME, ConfigConstants.DEFAULT_SECURITY_CONFIG_INDEX);
    this.authenticationBackend = authenticationBackend;
    this.authorizator = authorizator;
    this.httpAuthenticator = httpAuthenticator;
    this.sessionStore = sessionStore;

    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }//ww  w  .ja  v  a2 s  .co  m

    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
            @Override
            public Boolean run() throws Exception {
                method = RestController.class.getDeclaredMethod("getHandler", RestRequest.class);
                method.setAccessible(true);

                return true;
            }
        });
    } catch (final Exception e) {
        log.error(e.toString(), e);
        throw new ElasticsearchException(e.toString());
    }

    final String keyPath = settings.get(ConfigConstants.ARMOR_KEY_PATH, ".");
    //        AccessController.checkPermission(new FilePermission(keyPath+File.separator+"armor_node_key.key", "write"));
    SecretKey sc = null;
    try {
        sc = AccessController.doPrivileged(new PrivilegedExceptionAction<SecretKey>() {
            @Override
            public SecretKey run() throws Exception {
                final File keyFile = new File(keyPath, "armor_node_key.key");
                SecretKey sc = null;
                if (keyFile.exists()) {
                    log.debug("Loaded key from {}", keyFile.getAbsolutePath());
                    sc = new SecretKeySpec(FileUtils.readFileToByteArray(keyFile), "AES");
                } else {
                    final SecureRandom secRandom = SecureRandom.getInstance("SHA1PRNG");
                    final KeyGenerator kg = KeyGenerator.getInstance("AES");
                    kg.init(128, secRandom);
                    final SecretKey secretKey = kg.generateKey();
                    final byte[] enckey = secretKey.getEncoded();

                    if (enckey == null || enckey.length != 16) {
                        throw new Exception("invalid key " + (enckey == null ? -1 : enckey.length));
                    }
                    FileUtils.writeByteArrayToFile(keyFile, enckey);
                    sc = secretKey;
                    log.info("New key written to {}, make sure all nodes have this key",
                            keyFile.getAbsolutePath());
                }
                return sc;
            }
        });
    } catch (final Exception e) {
        log.error("Cannot generate or read secrety key", e);
        throw new ElasticsearchException(e.toString());
    }

    this.auditListener = auditListener;
    //TODO FUTURE index change audit trail

    final boolean checkForRoot = settings.getAsBoolean(ConfigConstants.ARMOR_CHECK_FOR_ROOT, true);

    if (SecurityUtil.isRootUser()) {

        if (checkForRoot) {
            throw new ElasticsearchException(
                    "You're trying to run elasticsearch as root or Windows Administrator and thats forbidden.");
        } else {
            log.warn(
                    "You're trying to run elasticsearch as root or Windows Administrator! Thats a potential security issue.");
        }

    }

    /*final String scriptingStatus = settings.get(ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING,
        ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT);
            
    if (scriptingStatus.equalsIgnoreCase(ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT)) {
    log.warn("{} has the default value {}, consider setting it to false if not needed",
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING, scriptingStatus);
    }
            
    if (scriptingStatus.equalsIgnoreCase("true")) {
    log.error("{} is configured insecure, consider setting it to false or " + ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT,
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING);
    }*/
    if (searchService == null) {
        throw new RuntimeException("ssnull");
    }

    ArmorService.secretKey = sc;
}

From source file:com.sshtools.daemon.forwarding.ForwardingServer.java

/**
 *
 *
 * @param addressToBind/*from  w w  w  .j a  v a 2  s  . co m*/
 * @param portToBind
 *
 * @throws ForwardingConfigurationException
 */
protected void addRemoteForwardingConfiguration(String addressToBind, int portToBind)
        throws ForwardingConfigurationException {
    // Is the server already listening
    Iterator it = remoteForwardings.iterator();
    ForwardingConfiguration config;

    while (it.hasNext()) {
        config = (ForwardingConfiguration) it.next();

        if (config.getAddressToBind().equals(addressToBind) && (config.getPortToBind() == portToBind)) {
            throw new ForwardingConfigurationException("The address and port are already in use!");
        }
    }

    config = new ForwardingConfiguration(addressToBind, portToBind);

    // Check the security mananger
    SecurityManager manager = System.getSecurityManager();

    if (manager != null) {
        try {
            manager.checkPermission(
                    new SocketPermission(addressToBind + ":" + String.valueOf(portToBind), "accept,listen"));
        } catch (SecurityException e) {
            throw new ForwardingConfigurationException("The security manager has denied listen permision on "
                    + addressToBind + ":" + String.valueOf(portToBind));
        }
    }

    try {
        ForwardingListener listener = new ServerForwardingListener(connection, addressToBind, portToBind);
        remoteForwardings.add(listener);
        listener.start();
    } catch (IOException ex) {
        throw new ForwardingConfigurationException(ex.getMessage());
    }
}

From source file:com.ideabase.repository.core.service.UserServiceImpl.java

/**
 * {@inheritDoc}//from  w ww .ja v a2s  .c  o m
 */
public boolean isAllowed(final Subject pSubject, final Permission pPermission) {
    final SecurityManager securityManager;
    if (System.getSecurityManager() == null) {
        mLog.debug("No predefined security manager found.");
        securityManager = new SecurityManager();
    } else {
        securityManager = System.getSecurityManager();
    }

    try {
        mLog.debug("Do as privileged action.");
        Subject.doAsPrivileged(pSubject, new PrivilegedAction() {
            public Object run() {
                securityManager.checkPermission(pPermission);
                return null;
            }
        }, null);
        mLog.debug("user action is previleged.");
        return true;
    } catch (RuntimeException e) {
        // No logging here, because, if exception raised it refers to permission
        // failure.
        mLog.warn("Exception raised during verifying the authorization", e);
        return false;
    }
}

From source file:org.elasticsearch.xpack.qa.sql.security.SqlSecurityTestCase.java

@Before
public void setInitialAuditLogOffset() {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }//from   w  w  w.ja v a2 s.  com
    AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
        if (false == Files.exists(AUDIT_LOG_FILE)) {
            auditLogWrittenBeforeTestStart = 0;
            return null;
        }
        if (false == Files.isRegularFile(AUDIT_LOG_FILE)) {
            throw new IllegalStateException(
                    "expected tests.audit.logfile [" + AUDIT_LOG_FILE + "]to be a plain file but wasn't");
        }
        try {
            auditLogWrittenBeforeTestStart = Files.size(AUDIT_LOG_FILE);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    });
}