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(String message, Throwable cause) 

Source Link

Document

Creates a SecurityException with the specified detail message and cause.

Usage

From source file:info.magnolia.cms.security.SecurityUtil.java

public static void updateKeys(MgnlKeyPair keys) {
    // update filestore only when private key is present
    if (keys.getPrivateKey() != null) {
        String path = SystemProperty.getProperty(KEY_LOCATION_PROPERTY);
        try {//from  ww w .  ja  v  a 2  s.c o  m
            Properties defaultProps = new Properties();
            defaultProps.put(PRIVATE_KEY, keys.getPrivateKey());
            defaultProps.put(PUBLIC_KEY, keys.getPublicKey());
            File keystore = new File(path);
            File parentFile = keystore.getParentFile();
            if (parentFile != null) {
                parentFile.mkdirs();
            }
            FileWriter writer = new FileWriter(keystore);
            String date = new SimpleDateFormat("dd.MMM.yyyy hh:mm").format(new Date());
            defaultProps.store(writer, "generated " + date + " by " + MgnlContext.getUser().getName());
            writer.close();
        } catch (FileNotFoundException e) {
            throw new SecurityException(
                    "Failed to store private key. Please make sure the key is located in " + path, e);
        } catch (IOException e) {
            throw new SecurityException(
                    "Failed to store private key. Please make sure the key is located in " + path, e);
        }
    }
    try {
        Session session = MgnlContext.getSystemContext().getJCRSession("config");
        session.getNode("/server/activation").setProperty("publicKey", keys.getPublicKey());
        session.save();
    } catch (RepositoryException e) {
        throw new SecurityException("Failed to store public key.", e);
    }
}

From source file:com.cws.esolutions.security.utils.PasswordUtils.java

/**
 * Base64 decodes a given string/*  w  ww .  j  ava 2 s . c om*/
 *
 * @param variance - The allowed differences in OTP values
 * @param algorithm - The algorithm to encrypt the data with
 * @param instance - The security instance to utilize
 * @param secret - The OTP secret
 * @param code - The OTP code
 * @return <code>true</code> if successful, <code>false</code> otherwise
 * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing
 */
public static final boolean validateOtpValue(final int variance, final String algorithm, final String instance,
        final String secret, final int code) throws SecurityException {
    final String methodName = PasswordUtils.CNAME
            + "#validateOtpValue(final int variance, final String algorithm, final String instance, final String secret, final int code) throws SecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", variance);
        DEBUGGER.debug("Value: {}", algorithm);
        DEBUGGER.debug("Value: {}", instance);
        DEBUGGER.debug("Value: {}", secret);
        DEBUGGER.debug("Value: {}", code);
    }

    long truncatedHash = 0;
    byte[] data = new byte[8];
    long timeIndex = System.currentTimeMillis() / 1000 / 30;

    final Base32 codec = new Base32();
    final byte[] decoded = codec.decode(secret);
    SecretKeySpec signKey = new SecretKeySpec(decoded, algorithm);

    if (DEBUG) {
        DEBUGGER.debug("long: {}", timeIndex);
    }

    try {
        for (int i = 8; i-- > 0; timeIndex >>>= 8) {
            data[i] = (byte) timeIndex;
        }

        Mac mac = Mac.getInstance(instance);
        mac.init(signKey);
        byte[] hash = mac.doFinal(data);
        int offset = hash[20 - 1] & 0xF;

        for (int i = 0; i < 4; i++) {
            truncatedHash <<= 8;
            truncatedHash |= (hash[offset + i] & 0xFF);
        }

        truncatedHash &= 0x7FFFFFFF;
        truncatedHash %= 1000000;

        if (DEBUG) {
            DEBUGGER.debug("truncatedHash: {}", truncatedHash);
        }

        return (truncatedHash == code);
    } catch (InvalidKeyException ikx) {
        throw new SecurityException(ikx.getMessage(), ikx);
    } catch (NoSuchAlgorithmException nsx) {
        throw new SecurityException(nsx.getMessage(), nsx);
    }
}

From source file:de.itsvs.cwtrpc.controller.RemoteServiceControllerServlet.java

protected String invokeAndEncodeResponse(HttpServletRequest servletRequest, HttpServletResponse response,
        Object service, RPCRequest rpcRequest)
        throws ServletException, IOException, SecurityException, SerializationException {
    String responsePayload;/* w  w w.j a  v a 2  s  . co m*/

    try {
        final Object invocationResult;

        invocationResult = rpcRequest.getMethod().invoke(service, rpcRequest.getParameters());
        responsePayload = RPC.encodeResponseForSuccess(rpcRequest.getMethod(), invocationResult,
                rpcRequest.getSerializationPolicy(), rpcRequest.getFlags());

        if (CwtRpcUtils.getRpcSessionInvalidationPolicy(servletRequest).isInvalidateAfterInvocation()) {
            invalidateSession(servletRequest);
        }
    } catch (IllegalAccessException e) {
        throw new SecurityException("Illegal access detected when invoking method " + rpcRequest.getMethod()
                + " on service " + service.getClass().getName() + " (as requested by client)", e);
    } catch (IllegalArgumentException e) {
        throw new SecurityException(
                "Illegal argument types detected when invoking method " + rpcRequest.getMethod()
                        + " with arguments \"" + createTypeNameString(rpcRequest.getParameters())
                        + "\" on service " + service.getClass().getName() + " (as requested by client)",
                e);
    } catch (InvocationTargetException e) {
        responsePayload = processInvocationException(servletRequest, service, rpcRequest, e.getCause());
    }

    return responsePayload;
}

From source file:com.cws.esolutions.security.processors.impl.AccountChangeProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IAccountChangeProcessor#enableOtpAuth(com.cws.esolutions.security.processors.dto.AccountChangeRequest)
 *//*ww w.  ja va2  s.co  m*/
public AccountChangeResponse enableOtpAuth(final AccountChangeRequest request) throws AccountChangeException {
    final String methodName = IAccountChangeProcessor.CNAME
            + "#enableOtpAuth(final AccountChangeRequest request) throws AccountChangeException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("AccountChangeRequest: {}", request);
    }

    AccountChangeResponse response = new AccountChangeResponse();

    final UserAccount requestor = request.getRequestor();
    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final AuthenticationData reqSecurity = request.getUserSecurity();

    if (DEBUG) {
        DEBUGGER.debug("UserAccount: {}", userAccount);
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount: {}", userAccount);
    }

    if (!(StringUtils.equals(userAccount.getGuid(), requestor.getGuid()))) {
        // requesting user is not the same as the user being reset. authorize
        response.setRequestStatus(SecurityRequestStatus.UNAUTHORIZED);

        return response;
    }

    try {
        String userSalt = userSec.getUserSalt(userAccount.getGuid(), SaltType.LOGON.name());

        if (StringUtils.isNotEmpty(userSalt)) {
            // we aren't getting the data back here because we don't need it. if the request
            // fails we'll get an exception and not process further. this might not be the
            // best flow control, but it does exactly what we need where we need it.
            authenticator.performLogon(userAccount.getUsername(),
                    PasswordUtils.encryptText(reqSecurity.getPassword(), userSalt,
                            secBean.getConfigData().getSecurityConfig().getAuthAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getIterations(),
                            secBean.getConfigData().getSystemConfig().getEncoding()));

            String secret = new String(
                    new Base32().encode(RandomStringUtils.randomAlphanumeric(10).getBytes()));

            if (DEBUG) {
                DEBUGGER.debug("String: {}", secret);
            }

            String otpSalt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

            if (StringUtils.isNotEmpty(otpSalt)) {
                boolean isSaltInserted = userSec.addOrUpdateSalt(userAccount.getGuid(), otpSalt,
                        SaltType.OTP.name());

                if (DEBUG) {
                    DEBUGGER.debug("isSaltInserted: {}", isSaltInserted);
                }

                if ((!isSaltInserted)) {
                    response.setRequestStatus(SecurityRequestStatus.FAILURE);

                    return response;
                }

                boolean isComplete = userManager.modifyOtpSecret(userAccount.getUsername(), true,
                        PasswordUtils.encryptText(secret, otpSalt,
                                secBean.getConfigData().getSecurityConfig().getSecretAlgorithm(),
                                secBean.getConfigData().getSecurityConfig().getIterations(),
                                secBean.getConfigData().getSecurityConfig().getKeyBits(),
                                secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                                secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                                secBean.getConfigData().getSystemConfig().getEncoding()));

                if (DEBUG) {
                    DEBUGGER.debug("isComplete: {}", isComplete);
                }

                if (!(isComplete)) {
                    response.setRequestStatus(SecurityRequestStatus.FAILURE);

                    return response;
                }

                String qrCodeData = String.format(IAccountChangeProcessor.KEY_URI_FORMAT,
                        userAccount.getUsername(), secret, request.getApplicationName(),
                        secConfig.getOtpAlgorithm());

                if (DEBUG) {
                    DEBUGGER.debug("qrCodeData: {}", qrCodeData);
                }

                ByteArrayOutputStream qrCode = QRCode.from(qrCodeData.trim()).to(ImageType.PNG).stream();

                if (DEBUG) {
                    DEBUGGER.debug("ByteArrayOutputStream: {}", qrCode);
                }

                response.setSecret(secret);
                response.setQrCode(qrCode);
                response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            } else {
                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        } else {
            ERROR_RECORDER.error("Unable to obtain configured user salt. Cannot continue");

            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), sqx);

        throw new AccountChangeException(sqx.getMessage(), sqx);
    } catch (AuthenticatorException ax) {
        ERROR_RECORDER.error(ax.getMessage(), ax);

        throw new AccountChangeException(ax.getMessage(), ax);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new SecurityException(sx.getMessage(), sx);
    } catch (UserManagementException umx) {
        ERROR_RECORDER.error(umx.getMessage(), umx);

        throw new SecurityException(umx.getMessage(), umx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.CHANGEKEYS);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getApplicationName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();
            auditRequest.setAuditEntry(auditEntry);

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:com.cws.esolutions.security.processors.impl.AccountChangeProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IAccountChangeProcessor#disableOtpAuth(com.cws.esolutions.security.processors.dto.AccountChangeRequest)
 *///  w w w. j  ava2  s. c o  m
public AccountChangeResponse disableOtpAuth(final AccountChangeRequest request) throws AccountChangeException {
    final String methodName = IAccountChangeProcessor.CNAME
            + "#disableOtpAuth(final AccountChangeRequest request) throws AccountChangeException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("AccountChangeRequest: {}", request);
    }

    AccountChangeResponse response = new AccountChangeResponse();

    final UserAccount requestor = request.getRequestor();
    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final AuthenticationData reqSecurity = request.getUserSecurity();

    if (DEBUG) {
        DEBUGGER.debug("UserAccount: {}", userAccount);
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount: {}", userAccount);
    }

    if (!(StringUtils.equals(userAccount.getGuid(), requestor.getGuid()))) {
        // requesting user is not the same as the user being reset. authorize
        response.setRequestStatus(SecurityRequestStatus.UNAUTHORIZED);

        return response;
    }

    try {
        String userSalt = userSec.getUserSalt(userAccount.getGuid(), SaltType.LOGON.name());

        if (StringUtils.isNotEmpty(userSalt)) {
            // we aren't getting the data back here because we don't need it. if the request
            // fails we'll get an exception and not process further. this might not be the
            // best flow control, but it does exactly what we need where we need it.
            authenticator.performLogon(userAccount.getUsername(),
                    PasswordUtils.encryptText(reqSecurity.getPassword(), userSalt,
                            secBean.getConfigData().getSecurityConfig().getAuthAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getIterations(),
                            secBean.getConfigData().getSystemConfig().getEncoding()));

            // delete entries here
            boolean isSecretRemoved = userManager.modifyOtpSecret(userAccount.getGuid(), false, null);

            if (DEBUG) {
                DEBUGGER.debug("isSecretRemoved: {}", isSecretRemoved);
            }

            if (!(isSecretRemoved)) {
                response.setRequestStatus(SecurityRequestStatus.FAILURE);

                return response;
            }

            boolean isSaltRemoved = userSec.removeUserData(userAccount.getGuid(), SaltType.OTP.name());

            if (DEBUG) {
                DEBUGGER.debug("isSaltRemoved: {}", isSaltRemoved);
            }

            if (!(isSaltRemoved)) {
                response.setRequestStatus(SecurityRequestStatus.FAILURE);

                return response;
            }

            response.setRequestStatus(SecurityRequestStatus.SUCCESS);
        } else {
            ERROR_RECORDER.error("Unable to obtain configured user salt. Cannot continue");

            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), sqx);

        throw new AccountChangeException(sqx.getMessage(), sqx);
    } catch (AuthenticatorException ax) {
        ERROR_RECORDER.error(ax.getMessage(), ax);

        throw new AccountChangeException(ax.getMessage(), ax);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new SecurityException(sx.getMessage(), sx);
    } catch (UserManagementException umx) {
        ERROR_RECORDER.error(umx.getMessage(), umx);

        throw new SecurityException(umx.getMessage(), umx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.CHANGEKEYS);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getApplicationName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();
            auditRequest.setAuditEntry(auditEntry);

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}