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:eu.forgestore.ws.util.ShiroUTAuthorizingRealm.java

public boolean validate(UsernameToken usernameToken) throws LoginException {

    if (usernameToken == null) {
        throw new SecurityException("noCredential");
    }/*www  . j  a  v a2 s.c  o m*/
    // Validate the UsernameToken

    String pwType = usernameToken.getPasswordType();
    logger.info("UsernameToken user " + usernameToken.getName());
    logger.info("UsernameToken password " + usernameToken.getPassword());
    logger.info("UsernameToken password type " + pwType);

    // if (!WSConstants.PASSWORD_TEXT.equals(pwType)) {
    // if (log.isDebugEnabled()) {
    // logger.debug("Authentication failed - digest passwords are not accepted");
    // }
    // throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    // }

    if (usernameToken.getPassword() == null) {

        logger.debug("Authentication failed - no password was provided");

        throw new FailedLoginException("Sorry! No login for you.");
    }

    // Validate it via Shiro
    Subject currentUser = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(usernameToken.getName(),
            usernameToken.getPassword());
    token.setRememberMe(true);
    try {
        currentUser.login(token);
    } catch (AuthenticationException ex) {
        logger.info(ex.getMessage(), ex);
        throw new FailedLoginException("Sorry! No login for you.");
    }
    // Perform authorization check
    if (!requiredRoles.isEmpty() && !currentUser.hasAllRoles(requiredRoles)) {
        logger.info("Authorization failed for authenticated user");
        throw new FailedLoginException("Sorry! No login for you.");
    }

    boolean succeeded = true;

    return succeeded;
}

From source file:net.es.netshell.kernel.users.Users.java

@SysCall(name = "do_authUser")
public void do_authUser(String user, String password)
        throws NonExistentUserException, UserException, UserClassException {
    logger.info("do_authUser entry");
    if (BootStrap.getBootStrap().isStandAlone()) {
        throw new SecurityException("not allowed");
    }/*  ww  w  .ja va2  s .  c  o  m*/
    // Read file.
    try {
        this.readUserFile();
    } catch (IOException e) {
        logger.error("Cannot read password file");
    }

    if (this.passwords.isEmpty()) {
        // No user has been created. Will accept "admin","netshell".
        // TODO: default admin user should be configured in a safer way.
        if (Users.ADMIN_USERNAME.equals(user) && Users.ADMIN_PASSWORD.equals(password)) {
            // Create the initial configuration file
            try {

                // Set up the default admin user.  This takes basically two steps.
                // First we need to create the user's entry in the user file.
                // Then we need to get a User object from that, so we can be running
                // as that initial user.  Finally this allows us to create a container.
                UserProfile adminProfile = new UserProfile(Users.ADMIN_USERNAME, Users.ADMIN_PASSWORD,
                        Users.ROOT, "Admin", "Admin", "admin@localhost");
                this.do_createUser(adminProfile, false);

            } catch (UserAlreadyExistException e) {
                // Since this code is executed only when the configuration file is empty, this should never happen.
                logger.error("User {} already exists in empty configuration file", Users.ADMIN_USERNAME);
            } catch (IOException e) {
                // This shouldn't happen either...it means we couldn't create the initial password file.
                logger.error("Cannot create initial password file");
            }
        }
    }

    logger.warn("looking for key for {}", user);
    if (!Users.getUsers().passwords.containsKey(user)) {
        logger.warn("{} is unknown", user);
    }
    UserProfile userProfile = Users.getUsers().passwords.get(user);
    if (userProfile.getPassword().equals("*")) {
        // Disable password
        throw new UserException("not authorized");
    }

    // Local password verification here.  Check an encrypted version of the user's password
    // against what was stored in password file, a la UNIX password authentication.
    if (userProfile.getPassword().equals(crypt(password, userProfile.getPassword()))) {
        logger.warn("{} has entered correct password", user);

    } else {
        logger.warn("{} has entered incorrect password", user);
        throw new UserException(user);
    }
}

From source file:com.infosupport.ellison.core.archive.ApplicationArchive.java

/**
 * Gets a file from inside the application archive.
 * <p/>//w w  w . j  a  v  a  2 s. c om
 * Note that this method calls {@link #unpackJar()}, so if the archive hasn't yet been unpacked, this method may
 * throw an {@code IOException}.
 *
 * @param relativePath
 *     the path of the file to find. This must be a relative path.
 *
 * @return a pointer to the queried file.
 *
 * @throws IOException
 *     if an error occurred while trying to unpack the application archive, or if the supplied path does not point
 *     to a file within the application archive (in which case the exception will be an instance of {@link
 *     FileNotFoundException}.
 */
public File getFile(String relativePath) throws IOException {
    File foundFile = null;

    if (!isPathRelative(relativePath)) {
        throw new SecurityException("Supplied paths must be relative!");
    }

    foundFile = new File(unpackedPath, relativePath);

    if (!foundFile.exists()) {
        throw new FileNotFoundException(String.format("No file '%s' in application archive", relativePath));
    }

    return foundFile;
}

From source file:org.apache.hadoop.hive.llap.daemon.impl.LlapTokenChecker.java

@VisibleForTesting
static void checkPermissionsInternal(String kerberosName, List<LlapTokenIdentifier> tokens, String userName,
        String appId, Object hint) {
    if (appId == null) {
        appId = "";
    }/*from  w  w  w  . j  av  a  2s .  c  om*/
    if (kerberosName != null && StringUtils.isBlank(appId) && kerberosName.equals(userName)) {
        return;
    }
    if (tokens != null) {
        for (LlapTokenIdentifier llapId : tokens) {
            String tokenUser = llapId.getOwner().toString(), tokenAppId = llapId.getAppId();
            if (checkTokenPermissions(userName, appId, tokenUser, tokenAppId))
                return;
        }
    }
    throw new SecurityException("Unauthorized to access " + userName + ", " + appId + " (" + hint + ")");
}

From source file:org.jumpmind.symmetric.transport.http.HttpIncomingTransport.java

/**
 * This method support redirection from an http connection to an https connection.
 * See {@link http://java.sun.com/j2se/1.4.2/docs/guide/deployment/deployment-guide/upgrade-guide/article-17.html}
 * for more information.//from w  w w.j  a  va 2s  . c o m
 * 
 * @param connection
 * @return
 * @throws IOException
 */
private HttpURLConnection openConnectionCheckRedirects(HttpURLConnection connection) throws IOException {
    boolean redir;
    int redirects = 0;
    do {
        connection.setInstanceFollowRedirects(false);
        redir = false;
        int stat = connection.getResponseCode();
        if (stat >= 300 && stat <= 307 && stat != 306 && stat != HttpURLConnection.HTTP_NOT_MODIFIED) {
            URL base = connection.getURL();
            redirectionUrl = connection.getHeaderField("Location");

            URL target = null;
            if (redirectionUrl != null) {
                target = new URL(base, redirectionUrl);
            }
            connection.disconnect();
            // Redirection should be allowed only for HTTP and HTTPS
            // and should be limited to 5 redirections at most.
            if (target == null || !(target.getProtocol().equals("http") || target.getProtocol().equals("https"))
                    || redirects >= 5) {
                throw new SecurityException("illegal URL redirect");
            }
            redir = true;
            connection = HttpTransportManager.openConnection(target, getBasicAuthUsername(),
                    getBasicAuthPassword());
            connection.setConnectTimeout(httpTimeout);
            connection.setReadTimeout(httpTimeout);

            redirects++;
        }
    } while (redir);

    return connection;
}

From source file:org.apache.bookkeeper.tls.TLSContextFactory.java

private TrustManagerFactory initTrustManagerFactory(String trustStoreType, String trustStoreLocation,
        String trustStorePasswordPath) throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, SecurityException {
    TrustManagerFactory tmf;//  w ww.  j  av  a2 s .c  o m

    if (Strings.isNullOrEmpty(trustStoreLocation)) {
        LOG.error("Trust Store location cannot be empty!");
        throw new SecurityException("Trust Store location cannot be empty!");
    }

    String trustStorePassword = "";
    if (!Strings.isNullOrEmpty(trustStorePasswordPath)) {
        trustStorePassword = getPasswordFromFile(trustStorePasswordPath);
    }

    // Initialize trust file
    KeyStore ts = loadKeyStore(trustStoreType, trustStoreLocation, trustStorePassword);
    tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ts);

    return tmf;
}

From source file:org.kawanfw.file.servlet.ServerLoginAction.java

/**
 * /*from w w w.  j  a v  a2s  . c  o  m*/
 * Execute the login request asked by the main File Servlet
 * 
 * @param request
 *            the http request
 * @param response
 *            the http response
 * @param commonsConfigurator
 *            the Commons Client login specific class
 * @param action
 *            the login action: BEFORE_LOGIN_ACTION or LOGIN_ACTION
 * @throws IOException
 *             if any Servlet Exception occurs
 */
public void executeAction(HttpServletRequest request, HttpServletResponse response,
        CommonsConfigurator commonsConfigurator, String action) throws IOException {
    PrintWriter out = response.getWriter();

    try {
        response.setContentType("text/html");

        // if the action is BEFORE_LOGIN_ACTION: just test if we must be in
        // https mode
        if (action.equals(Action.BEFORE_LOGIN_ACTION)) {
            // Check if we must be in httpS
            // boolean forceHttps =
            // commonsConfigurator.forceSecureHttp();
            boolean forceHttps = CommonsConfiguratorCall.forceSecureHttp(commonsConfigurator);

            out.println(TransferStatus.SEND_OK);
            out.println(forceHttps);
            return;
        }

        debug("before request.getParameter(Parameter.LOGIN);");

        String username = request.getParameter(Parameter.USERNAME);
        username = username.trim();

        String password = request.getParameter(Parameter.PASSWORD);
        password = password.trim();

        // User must provide a user
        if (username.length() < 1) {
            debug("username.length() < 1!");
            // No login transmitted
            // Redirect to ClientLogin with error message.
            out.println(TransferStatus.SEND_OK);
            out.println(ReturnCode.INVALID_LOGIN_OR_PASSWORD);
            return;
        }

        debug("before commonsConfigurator.getBannedUsernames();");

        // Check the username. Refuse access if username is banned
        // Set<String> usernameSet =
        // commonsConfigurator.getBannedUsernames();
        Set<String> usernameSet = CommonsConfiguratorCall.getBannedUsernames(commonsConfigurator);

        if (usernameSet.contains(username)) {
            debug("banned username!");
            throw new SecurityException("Username is banned: " + usernameSet);
        }

        // Check the IP. Refuse access if IP is banned/blacklisted
        String ip = request.getRemoteAddr();

        debug("before commonsConfigurator.getIPsWhitelist();");
        List<String> whitelistedIpList = CommonsConfiguratorCall.getIPsWhitelist(commonsConfigurator);

        if (DEBUG) {
            log("Printing whitelisted IPs...");
            for (String whitelistedIp : whitelistedIpList) {
                log("whitelisted IP: " + whitelistedIp);
            }
        }

        if (!IpUtil.isIpWhitelisted(ip, whitelistedIpList)) {
            debug("not whitelisted IP!");
            throw new SecurityException("Client IP is not whitelisted: " + ip);
        }

        // use blacklist only if whitelist is empty

        if (whitelistedIpList == null || whitelistedIpList.isEmpty()) {
            debug("before commonsConfigurator.getIPsBlacklist();");
            List<String> blacklistedIpList = CommonsConfiguratorCall.getIPsBlacklist(commonsConfigurator);

            if (DEBUG) {
                log("Printing blacklisted IPs...");
                for (String blacklistedIp : blacklistedIpList) {
                    log("blacklisted IP: " + blacklistedIp);
                }
            }

            if (IpUtil.isIpBlacklisted(ip, blacklistedIpList)) {
                debug("blacklisted IP!");
                throw new SecurityException("Client IP is blacklisted: " + ip);
            }
        }

        debug("calling checkLoginAndPassword");

        boolean isOk = commonsConfigurator.login(username, password.toCharArray());

        debug("login isOk: " + isOk + " (login: " + username + ")");

        if (!isOk) {
            debug("login: invalid login or password");

            // Reduce the login speed
            LoginSpeedReducer loginSpeedReducer = new LoginSpeedReducer(username);
            loginSpeedReducer.checkAttempts();

            out.println(TransferStatus.SEND_OK);
            out.println(ReturnCode.INVALID_LOGIN_OR_PASSWORD);
            return;
        }

        debug("Login done!");

        // OK! Now build a token with SHA-1(username + secretValue)
        String token = CommonsConfiguratorCall.computeAuthToken(commonsConfigurator, username);

        // out.println(HttpTransfer.SEND_OK + SPACE + ReturnCode.OK + SPACE
        // + token);
        out.println(TransferStatus.SEND_OK);
        out.println(ReturnCode.OK + SPACE + token);

    } catch (Exception e) {

        out.println(TransferStatus.SEND_FAILED);
        out.println(e.getClass().getName());
        out.println(ServerUserThrowable.getMessage(e));
        out.println(ExceptionUtils.getStackTrace(e)); // stack trace

        try {
            ServerLogger.getLogger().log(Level.WARNING,
                    Tag.PRODUCT_EXCEPTION_RAISED + " " + ServerUserThrowable.getMessage(e));
            ServerLogger.getLogger().log(Level.WARNING,
                    Tag.PRODUCT_EXCEPTION_RAISED + " " + ExceptionUtils.getStackTrace(e));
        } catch (Exception e1) {
            e1.printStackTrace();
            e1.printStackTrace(System.out);
        }

    }
}

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

/**
 * Execute the MetaData request/*from   w w w . j  av a 2 s . c  o m*/
 */
public void execute() throws Exception {
    // String action = request.getParameter(SqlAction.ACTION) ;

    String username = request.getParameter(Parameter.USERNAME);
    String methodName = request.getParameter(Parameter.METHOD_NAME);
    String connectionId = request.getParameter(ConnectionParms.CONNECTION_ID);

    // methodName = HtmlConverter.fromHtml(methodName);

    debug("Parameter.METHOD_NAME: " + methodName);

    Connection connection = null;

    if (connectionId.equals("0")) {
        try {
            connection = commonsConfigurator.getConnection();

            boolean isAllowed = SqlConfiguratorCall.allowGetMetaData(sqlConfigurator, username, connection);

            if (!isAllowed) {
                String message = Tag.PRODUCT_SECURITY + " Database Catalog Query not authorized.";
                throw new SecurityException(message);
            }

            DatabaseMetaData databaseMetaData = connection.getMetaData();

            // If methodName is getMetaData ==> just return the
            // DatabaseMetaData
            if (methodName.equals("getMetaData")) {
                DatabaseMetaDataHolder databaseMetaDataHolder = new DatabaseMetaDataHolder();
                databaseMetaDataHolder.setDatabaseMetaDataHolder(databaseMetaData);

                String jsonString = DatabaseMetaDataHolderTransport.toJson(databaseMetaDataHolder);
                jsonString = HtmlConverter.toHtml(jsonString);
                //out.println(TransferStatus.SEND_OK);
                //out.println(jsonString);
                ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);
                ServerSqlManager.writeLine(out, jsonString);

                return;
            } else if (methodName.equals("getCatalog")) {
                String catalog = connection.getCatalog();
                catalog = HtmlConverter.toHtml(catalog);
                //out.println(TransferStatus.SEND_OK);
                //out.println(catalog);
                ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);
                ServerSqlManager.writeLine(out, catalog);
            } else {
                // Call the DatabaseMetaData.method with reflection:
                callMetaDataFunction(request, out, connection);
            }
        } finally {
            // Release the connection
            ConnectionCloser.freeConnection(connection, sqlConfigurator);
        }
    } else {
        ConnectionStore connectionStore = new ConnectionStore(username, connectionId);
        connection = connectionStore.get();

        if (connection == null) {
            //out.println(TransferStatus.SEND_OK);
            //out.println(SqlReturnCode.SESSION_INVALIDATED);
            ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);
            ServerSqlManager.writeLine(out, SqlReturnCode.SESSION_INVALIDATED);
            return;
        }

        boolean isAllowed = SqlConfiguratorCall.allowGetMetaData(sqlConfigurator, username, connection);

        if (!isAllowed) {
            String message = Tag.PRODUCT_SECURITY + " Database Catalog Query not authorized.";
            throw new SecurityException(message);
        }

        DatabaseMetaData databaseMetaData = connection.getMetaData();

        // If methodName is getMetaData ==> just return the
        // DatabaseMetaData
        if (methodName.equals("getMetaData")) {
            DatabaseMetaDataHolder databaseMetaDataHolder = new DatabaseMetaDataHolder();
            databaseMetaDataHolder.setDatabaseMetaDataHolder(databaseMetaData);

            String jsonString = DatabaseMetaDataHolderTransport.toJson(databaseMetaDataHolder);
            jsonString = HtmlConverter.toHtml(jsonString);
            //out.println(TransferStatus.SEND_OK);
            //out.println(jsonString);
            ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);
            ServerSqlManager.writeLine(out, jsonString);
            return;
        } else if (methodName.equals("getCatalog")) {
            String catalog = connection.getCatalog();
            catalog = HtmlConverter.toHtml(catalog);
            //out.println(TransferStatus.SEND_OK);
            //out.println(catalog);
            ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);
            ServerSqlManager.writeLine(out, catalog);

        } else {
            // Call the DatabaseMetaData.method with reflection:
            callMetaDataFunction(request, out, connection);
        }
    }

}

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

/**
 * /*from   www . jav  a2  s .c  o m*/
 * Execute the login request
 * 
 * @param request
 *            the http request
 * @param response
 *            the http response
 * @param commonsConfigurator
 *            the Commons Client specific class
 * @param sqlConfigurator
 *            the client sql http configurator specific class
 * @param action
 *            the login action: BEFORE_LOGIN_ACTION or LOGIN_ACTION
 * @throws IOException
 *             if any Servlet Exception occurs
 */
public void executeAction(HttpServletRequest request, HttpServletResponse response,
        CommonsConfigurator commonsConfigurator, SqlConfigurator sqlConfigurator, String action)
        throws IOException {
    PrintWriter out = response.getWriter();

    try {
        response.setContentType("text/html");

        // if the action is BEFORE_LOGIN_ACTION: just test if we must be in
        // https mode
        if (action.equals(Action.BEFORE_LOGIN_ACTION)) {
            // Check if we must be in httpS
            boolean forceHttps = CommonsConfiguratorCall.forceSecureHttp(commonsConfigurator);

            out.println(TransferStatus.SEND_OK);
            out.println(forceHttps);
            return;
        }

        debug("before request.getParameter(Parameter.LOGIN);");

        String username = request.getParameter(Parameter.USERNAME);
        username = username.trim();

        String password = request.getParameter(Parameter.PASSWORD);
        password = password.trim();

        // User must provide a user
        if (username.length() < 1) {
            debug("username.length() < 1!");
            // No login transmitted
            // Redirect to ClientLogin with error message.
            out.println(TransferStatus.SEND_OK);
            out.println(ReturnCode.INVALID_LOGIN_OR_PASSWORD);
            return;
        }

        debug("before CommonsConfigurator.getBannedUsernames();");

        // Check the username. Refuse access if username is banned
        Set<String> usernameSet = CommonsConfiguratorCall.getBannedUsernames(commonsConfigurator);

        if (usernameSet.contains(username)) {
            debug("banned username!");
            throw new SecurityException("Username is banned: " + usernameSet);
        }

        // Check the IP. Refuse access if IP is banned/blacklisted
        String ip = request.getRemoteAddr();

        debug("before commonsConfigurator.getIPsWhitelist();");
        List<String> whitelistedIpList = CommonsConfiguratorCall.getIPsWhitelist(commonsConfigurator);

        if (DEBUG) {
            log("Printing whitelisted IPs...");
            for (String whitelistedIp : whitelistedIpList) {
                log("whitelisted IP: " + whitelistedIp);
            }
        }

        if (!IpUtil.isIpWhitelisted(ip, whitelistedIpList)) {
            debug("not whitelisted IP!");
            throw new SecurityException("Client IP is not whitelisted: " + ip);
        }

        // use blacklist only if whitelist is empty

        if (whitelistedIpList == null || whitelistedIpList.isEmpty()) {
            debug("before commonsConfigurator.getIPsBlacklist();");
            List<String> blacklistedIpList = CommonsConfiguratorCall.getIPsBlacklist(commonsConfigurator);

            if (DEBUG) {
                log("Printing blacklisted IPs...");
                for (String blacklistedIp : blacklistedIpList) {
                    log("blacklisted IP: " + blacklistedIp);
                }
            }

            if (IpUtil.isIpBlacklisted(ip, blacklistedIpList)) {
                debug("blacklisted IP!");
                throw new SecurityException("Client IP is blacklisted: " + ip);
            }
        }

        debug("calling checkLoginAndPassword");

        boolean isOk = commonsConfigurator.login(username, password.toCharArray());

        debug("login isOk: " + isOk + " (login: " + username + ")");

        if (!isOk) {
            debug("login: invalid login or password");

            out.println(TransferStatus.SEND_OK);
            out.println(ReturnCode.INVALID_LOGIN_OR_PASSWORD);
            return;
        }

        debug("Login done!");

        // OK! Now build a token with SHA-1(username + secretValue)
        String token = CommonsConfiguratorCall.computeAuthToken(commonsConfigurator, username);

        // out.println(HttpTransfer.SEND_OK + SPACE + ReturnCode.OK + SPACE
        // + token);
        out.println(TransferStatus.SEND_OK);
        out.println(ReturnCode.OK + SPACE + token);

    } catch (Exception e) {

        out.println(TransferStatus.SEND_FAILED);
        out.println(e.getClass().getName());
        out.println(ServerUserThrowable.getMessage(e));
        out.println(ExceptionUtils.getStackTrace(e)); // stack trace

        try {
            ServerLogger.getLogger().log(Level.WARNING,
                    Tag.PRODUCT_EXCEPTION_RAISED + " " + ServerUserThrowable.getMessage(e));
            ServerLogger.getLogger().log(Level.WARNING,
                    Tag.PRODUCT_EXCEPTION_RAISED + " " + ExceptionUtils.getStackTrace(e));
        } catch (Exception e1) {
            e1.printStackTrace();
            e1.printStackTrace(System.out);
        }

    }
}