Example usage for java.lang SecurityException SecurityException

List of usage examples for java.lang SecurityException SecurityException

Introduction

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

Prototype

public SecurityException(Throwable cause) 

Source Link

Document

Creates a SecurityException with the specified cause and a detail message of (cause==null ?

Usage

From source file:com.ikanow.aleph2.security.service.SecuredCrudManagementDbService.java

protected void checkDeletePermission() {

    boolean permitted = securityService.hasUserRole(principalName, ISecurityService.ROLE_ADMIN);
    if (!permitted) {
        String msg = "Subject " + principalName + " has no write permissions for deletions";
        logger.error(msg);/*w w  w  . j a  v a  2s  .c o m*/
        throw new SecurityException(msg);
    }

}

From source file:ezbake.deployer.EzBakeDeployerHandler.java

private void checkSecurityToken(EzSecurityToken token) throws DeploymentException {
    //Only the deployer and INS can deploy
    try {/* w  ww  .  ja va2  s .c om*/
        securityClient.validateReceivedToken(token);
    } catch (EzSecurityTokenException e) {
        log.error("Token validation failed. ", e);
        throw new DeploymentException("Token failed validation");
    }

    String fromId = token.getValidity().getIssuedTo();
    String forId = token.getValidity().getIssuedFor();
    if (!fromId.equals(forId) && !fromId.equals(insSecurityId)) {
        throw new SecurityException(String.format(
                "This call can only be made from INS (%s) or Deployer services. From: %s - To: %s",
                insSecurityId, fromId, forId));
    }
}

From source file:hudson.cli.CLI.java

/**
 * Attempts to lift the security restriction on the underlying channel.
 * This requires the administer privilege on the server.
 *
 * @throws SecurityException/*from  w w  w  .j  a va  2s.  co m*/
 *      If we fail to upgrade the connection.
 */
public void upgrade() {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    if (execute(Arrays.asList("groovy", "="),
            new ByteArrayInputStream("hudson.remoting.Channel.current().setRestricted(false)".getBytes()), out,
            out) != 0)
        throw new SecurityException(out.toString()); // failed to upgrade
}

From source file:org.mariotaku.twidere.provider.TwidereDataProvider.java

private void checkReadPermission(final int id, final String table, final String[] projection) {
    switch (id) {
    case VIRTUAL_TABLE_ID_CONSUMER_KEY_SECRET: {
        if (!checkPermission(PERMISSION_ACCOUNTS))
            throw new SecurityException(
                    "Access database " + table + " requires level PERMISSION_LEVEL_ACCOUNTS");
        break;// w  w  w.  java 2 s . c om
    }
    case TABLE_ID_ACCOUNTS: {
        // Reading some infomation like user_id, screen_name etc is
        // okay, but reading columns like password requires higher
        // permission level.
        if (ArrayUtils.contains(projection, Accounts.BASIC_AUTH_PASSWORD, Accounts.OAUTH_TOKEN,
                Accounts.TOKEN_SECRET) && !checkPermission(PERMISSION_ACCOUNTS))
            throw new SecurityException("Access column " + ArrayUtils.toString(projection, ',', true)
                    + " in database accounts requires level PERMISSION_LEVEL_ACCOUNTS");
        if (!checkPermission(PERMISSION_READ))
            throw new SecurityException("Access database " + table + " requires level PERMISSION_LEVEL_READ");
        break;
    }
    case TABLE_ID_DIRECT_MESSAGES:
    case TABLE_ID_DIRECT_MESSAGES_INBOX:
    case TABLE_ID_DIRECT_MESSAGES_OUTBOX:
    case TABLE_ID_DIRECT_MESSAGES_CONVERSATION:
    case TABLE_ID_DIRECT_MESSAGES_CONVERSATION_SCREEN_NAME:
    case TABLE_ID_DIRECT_MESSAGES_CONVERSATIONS_ENTRY: {
        if (!checkPermission(PERMISSION_DIRECT_MESSAGES))
            throw new SecurityException(
                    "Access database " + table + " requires level PERMISSION_LEVEL_DIRECT_MESSAGES");
        break;
    }
    case TABLE_ID_STATUSES:
    case TABLE_ID_MENTIONS:
    case TABLE_ID_TABS:
    case TABLE_ID_DRAFTS:
    case TABLE_ID_CACHED_USERS:
    case TABLE_ID_FILTERED_USERS:
    case TABLE_ID_FILTERED_KEYWORDS:
    case TABLE_ID_FILTERED_SOURCES:
    case TABLE_ID_FILTERED_LINKS:
    case TABLE_ID_TRENDS_LOCAL:
    case TABLE_ID_CACHED_STATUSES:
    case TABLE_ID_CACHED_HASHTAGS: {
        if (!checkPermission(PERMISSION_READ))
            throw new SecurityException("Access database " + table + " requires level PERMISSION_LEVEL_READ");
        break;
    }
    }
}

From source file:oracle.kv.hadoop.hive.table.TableStorageHandlerBase.java

private void configureKVSecurityProperties(Properties tblProperties, Map<String, String> jobProperties) {

    final String loginFile = tblProperties.getProperty(KVSecurityConstants.SECURITY_FILE_PROPERTY);
    if (loginFile != null) {
        jobProperties.put(KVSecurityConstants.SECURITY_FILE_PROPERTY, loginFile);
        jobConf.set(KVSecurityConstants.SECURITY_FILE_PROPERTY, loginFile);
    }/*from  www.  ja v a 2s  . c o  m*/

    final String trustFile = tblProperties.getProperty(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY);
    if (trustFile != null) {
        jobProperties.put(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY, trustFile);
        jobConf.set(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY, trustFile);
    }

    final String username = tblProperties.getProperty(KVSecurityConstants.AUTH_USERNAME_PROPERTY);
    if (username != null) {
        jobProperties.put(KVSecurityConstants.AUTH_USERNAME_PROPERTY, username);
        jobConf.set(KVSecurityConstants.AUTH_USERNAME_PROPERTY, username);
    }

    /* Determine if wallet or password file and get file/dir name. */
    Integer passwordOrWallet = null; /* 0=file, 1=wallet, null=no pwd */

    String passwordLocProp = KVSecurityConstants.AUTH_WALLET_PROPERTY;
    String passwordLoc = tblProperties.getProperty(passwordLocProp);

    if (passwordLoc != null) {
        passwordOrWallet = 1;
    } else {
        passwordLocProp = KVSecurityConstants.AUTH_PWDFILE_PROPERTY;
        passwordLoc = tblProperties.getProperty(passwordLocProp);
        if (passwordLoc != null) {
            passwordOrWallet = 0;
        }
    }

    /*
     * The tblProperties from tableDesc are populated from the various
     * system property values specified via the TBLPROPERTIES directive
     * when the Hive external table is created. If the query is to be
     * run against a secure store, then the username and either a password
     * file or a wallet must be specified; but the password itself is not
     * specified in TBLPROPERTIES. If the query is the type of query that
     * Hive executes by running a MapReduce job (rather than the type in
     * which the metadatastore is employed to execute the query from only
     * the Hive client), then the backend of the MapReduce job will not be
     * able to access the password file or wallet; and thus, will not be
     * able to obtain the password by reading the file or wallet, as is
     * done from the Hive client. This is because the file and the wallet
     * are not transferred from the frontend client side of the query to
     * the backend MapReduce side (the DataNodes) of the query. As a
     * result, the password must be retrieved here on the client side,
     * from the password file or wallet located on the client's local file
     * system, and then be directly placed in tblProperties (as well as
     * the jobProperties and jobConf). Because the Hive infrastructure
     * transfers the tblProperties to the backend, the MapReduce job uses
     * the transferred tblProperties it receives to obtain the password.
     */
    if (passwordLoc != null) {
        jobProperties.put(passwordLocProp, passwordLoc);
        jobConf.set(passwordLocProp, passwordLoc);

        PasswordStore passwordStore = null;

        if (passwordOrWallet != null) {

            PasswordManager storeMgr = null;
            if (passwordOrWallet == 1) {
                final File walletDirFd = new File(passwordLoc);
                if (walletDirFd.exists()) {
                    try {
                        storeMgr = PasswordManager.load(PasswordManager.WALLET_MANAGER_CLASS);
                    } catch (Exception e) {
                        e.printStackTrace(); /* Send to Hive log file. */
                        throw new SecurityException(e); /* Send to CLI. */
                    }
                    passwordStore = storeMgr.getStoreHandle(walletDirFd);
                }
            } else {
                final File passwordFileFd = new File(passwordLoc);
                if (passwordFileFd.exists()) {
                    try {
                        storeMgr = PasswordManager.load(PasswordManager.FILE_STORE_MANAGER_CLASS);
                    } catch (Exception e) {
                        e.printStackTrace(); /* Send to Hive log file. */
                        throw new SecurityException(e); /* Send to CLI. */
                    }
                    passwordStore = storeMgr.getStoreHandle(passwordFileFd);
                }
            }
        }

        if (passwordStore != null) {
            try {
                passwordStore.open(null);
                final Collection<String> secretAliases = passwordStore.getSecretAliases();
                final Iterator<String> aliasItr = secretAliases.iterator();
                final char[] userPassword = (aliasItr.hasNext() ? passwordStore.getSecret(aliasItr.next())
                        : null);
                final String password = String.valueOf(userPassword);

                tblProperties.put(ParamConstant.AUTH_USER_PWD_PROPERTY.getName(), password);
                jobProperties.put(ParamConstant.AUTH_USER_PWD_PROPERTY.getName(), password);
                jobConf.set(ParamConstant.AUTH_USER_PWD_PROPERTY.getName(), password);
            } catch (IOException e) {
                throw new SecurityException(e);
            } finally {
                passwordStore.discard();
            }
        }
    }
}

From source file:com.ikanow.aleph2.security.service.SecuredCrudManagementDbService.java

/**
 * Read permissions are the default permissions. 
 * @param new_object//from  w  w w .  j  a va 2  s.c  o m
 */
protected boolean checkReadPermissions(Object new_object, boolean throwOrReturn) {
    List<String> permissions = permissionExtractor.extractPermissionIdentifiers(new_object,
            Optional.of(ISecurityService.ACTION_READ));
    boolean permitted = false;
    if (permissions != null && permissions.size() > 0) {
        for (String permission : permissions) {
            permitted = securityService.isUserPermitted(principalName, permission);
            if (permitted) {
                break;
            }
        }
        if (!permitted && throwOrReturn) {
            String msg = "Subject '" + principalName + "' has no read permissions (" + permissions + ")for "
                    + new_object.getClass();
            logger.error(msg);
            throw new SecurityException(msg);
        }
    }
    return permitted;

}

From source file:org.kawanfw.sql.servlet.sql.ServerStatement.java

/**
 * Execute the passed SQL Statement and return: <br>
 * - The result set as a List of Maps for SELECT statements. <br>
 * - The return code for other statements
 * //  ww  w  . jav a 2s  . c  om
 * @param sqlOrder
 *            the qsql order
 * @param sqlParms
 *            the sql parameters
 * @param out
 *            the output stream where to write to result set output
 * 
 * 
 * @throws SQLException
 */
private void executeQueryOrUpdateStatement(OutputStream out) throws SQLException, IOException {

    String sqlOrder = statementHolder.getSqlOrder();

    debug("statementHolder: " + statementHolder.getSqlOrder());
    debug("sqlOrder       : " + sqlOrder);

    // sqlOrder = HtmlConverter.fromHtml(sqlOrder);

    if (statementHolder.isDoExtractResultSetMetaData()) {
        sqlOrder = DbVendorManager.addLimit1(sqlOrder, connection);
    }

    Statement statement = null;

    try {

        if (!SqlConfiguratorCall.allowStatementClass(sqlConfigurator, username, connection)) {
            String ipAddress = request.getRemoteAddr();

            SqlConfiguratorCall.runIfStatementRefused(sqlConfigurator, username, connection, ipAddress,
                    sqlOrder, new Vector<Object>());

            String message = Tag.PRODUCT_SECURITY + " [" + "{Statement not authorized}" + "{sql order: "
                    + sqlOrder + "}]";

            throw new SecurityException(message);
        }

        statement = connection.createStatement();
        ServerSqlUtil.setStatementProperties(statement, statementHolder);

        debug("before ServerPreparedStatementParameters");

        boolean isAllowedAfterAnalysis = sqlConfigurator.allowStatementAfterAnalysis(username, connection,
                sqlOrder, new Vector<Object>());

        if (!isAllowedAfterAnalysis) {

            String ipAddress = request.getRemoteAddr();

            SqlConfiguratorCall.runIfStatementRefused(sqlConfigurator, username, connection, ipAddress,
                    sqlOrder, new Vector<Object>());

            String message = Tag.PRODUCT_SECURITY + " [" + "{Statement not authorized}" + "{sql order: "
                    + sqlOrder + "}]";

            throw new SecurityException(message);
        }

        isAllowedAfterAnalysis = SqlConfiguratorCall.allowResultSetGetMetaData(sqlConfigurator, username,
                connection);

        if (statementHolder.isDoExtractResultSetMetaData() && !isAllowedAfterAnalysis) {
            String message = Tag.PRODUCT_SECURITY + " ResultSet.getMetaData() Query not authorized.";
            throw new SecurityException(message);
        }

        debug("before executeQuery() / executeUpdate(sqlOrder)");

        if (statementHolder.isExecuteUpdate()) {

            if (!SqlConfiguratorCall.allowExecuteUpdate(sqlConfigurator, username, connection)) {
                String ipAddress = request.getRemoteAddr();

                SqlConfiguratorCall.runIfStatementRefused(sqlConfigurator, username, connection, ipAddress,
                        sqlOrder, new Vector<Object>());

                String message = Tag.PRODUCT_SECURITY + " [" + "{Statement not authorized for ExecuteUpdate}"
                        + "{sql order: " + sqlOrder + "}]";

                throw new SecurityException(message);
            }

            int rc = -1;

            boolean usesAutoGeneratedKeys = false;

            if (statementHolder.getAutoGeneratedKeys() != -1) {
                rc = statement.executeUpdate(sqlOrder, statementHolder.getAutoGeneratedKeys());
                usesAutoGeneratedKeys = true;
            } else if (statementHolder.getColumnIndexesAutogenerateKeys().length != 0) {
                rc = statement.executeUpdate(sqlOrder, statementHolder.getColumnIndexesAutogenerateKeys());
                usesAutoGeneratedKeys = true;
            } else if (statementHolder.getColumnNamesAutogenerateKeys().length != 0) {
                rc = statement.executeUpdate(sqlOrder, statementHolder.getColumnNamesAutogenerateKeys());
                usesAutoGeneratedKeys = true;
            } else {
                rc = statement.executeUpdate(sqlOrder);
            }

            //br.write(TransferStatus.SEND_OK + CR_LF);
            //br.write(rc + CR_LF);
            ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);
            ServerSqlManager.writeLine(out, "" + rc);

            if (usesAutoGeneratedKeys) {
                ResultSet rs = null;

                try {
                    rs = statement.getGeneratedKeys();
                    ResultSetWriter resultSetWriter = new ResultSetWriter(request, out, commonsConfigurator,
                            fileConfigurator, sqlConfigurator, username, sqlOrder, statementHolder);
                    resultSetWriter.write(rs);
                } finally {
                    if (rs != null) {
                        rs.close();
                    }
                }
            }

        } else {
            ResultSet rs = null;

            try {

                if (statementHolder.isDoExtractResultSetMetaData()) {
                    statement.setMaxRows(1);
                } else {
                    ServerSqlUtil.setMaxRowsToReturn(statement, sqlConfigurator);
                }

                rs = statement.executeQuery(sqlOrder);
                //br.write(TransferStatus.SEND_OK + CR_LF);
                ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);

                if (statementHolder.isDoExtractResultSetMetaData()) {
                    ResultSetMetaDataWriter resultSetMetaDataWriter = new ResultSetMetaDataWriter(out,
                            commonsConfigurator, sqlConfigurator);
                    resultSetMetaDataWriter.write(rs);
                } else {
                    // print(rs, br);
                    ResultSetWriter resultSetWriter = new ResultSetWriter(request, out, commonsConfigurator,
                            fileConfigurator, sqlConfigurator, username, sqlOrder, statementHolder);
                    resultSetWriter.write(rs);
                }

            } finally {
                if (rs != null) {
                    rs.close();
                }
            }
        }
    } catch (SQLException e) {
        ServerLogger.getLogger().log(Level.WARNING, Tag.PRODUCT_EXCEPTION_RAISED + CR_LF + "Statement: "
                + sqlOrder + CR_LF + "- sql order: " + sqlOrder + CR_LF + "- exception: " + e.toString());
        throw e;
    } finally {
        IOUtils.closeQuietly(out);

        if (statement != null) {
            statement.close();
        }
    }
}

From source file:com.hippo.content.FileProvider.java

/**
 * After the FileProvider is instantiated, this method is called to provide the system with
 * information about the provider.//from w w w .  j  a  v  a 2s .c  om
 *
 * @param context A {@link Context} for the current component.
 * @param info A {@link ProviderInfo} for the new provider.
 */
@Override
public void attachInfo(Context context, ProviderInfo info) {
    super.attachInfo(context, info);

    // Sanity check our security
    if (info.exported) {
        throw new SecurityException("Provider must not be exported");
    }
    if (!info.grantUriPermissions) {
        throw new SecurityException("Provider must grant uri permissions");
    }

    mStrategy = getPathStrategy(context, info.authority);
}

From source file:org.onecmdb.core.utils.wsdl.OneCMDBWebServiceImpl.java

public RBACSession getRBACSession(String token) {
    ISession session = onecmdb.getSession(token);
    if (session == null) {
        throw new SecurityException("No Session found! Try to do auth() first!");
    }//from  w  w w. jav  a 2 s  .  c o  m
    return (session.getRBACSession());
}

From source file:com.auditbucket.engine.service.TrackService.java

TxRef findTx(String txRef, boolean fetchHeaders) {
    String userName = securityHelper.getLoggedInUser();
    SystemUser su = sysUserService.findByName(userName);

    if (su == null)
        throw new SecurityException("Not authorised");
    TxRef tx = trackDao.findTxTag(txRef, su.getCompany(), fetchHeaders);
    if (tx == null)
        return null;
    return tx;//  w ww  . ja v  a2s . c o m
}