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:info.magnolia.cms.security.SecurityUtil.java

public static String decrypt(String message, String encodedKey) throws SecurityException {
    try {/* w ww  .j  a  va 2  s .  co  m*/
        if (StringUtils.isBlank(encodedKey)) {
            throw new SecurityException(
                    "Activation key was not found. Please make sure your instance is correctly configured.");
        }

        // decode key
        byte[] binaryKey = hexToByteArray(encodedKey);

        // create RSA public key cipher
        Cipher pkCipher = Cipher.getInstance(ALGORITHM, "BC");
        try {
            // create private key
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PublicKey pk = kf.generatePublic(publicKeySpec);
            pkCipher.init(Cipher.DECRYPT_MODE, pk);

        } catch (InvalidKeySpecException e) {
            // decrypting with private key?
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PrivateKey pk = kf.generatePrivate(privateKeySpec);
            pkCipher.init(Cipher.DECRYPT_MODE, pk);
        }

        // decrypt
        String[] chunks = StringUtils.split(message, ";");
        if (chunks == null) {
            throw new SecurityException(
                    "The encrypted information is corrupted or incomplete. Please make sure someone is not trying to intercept or modify encrypted message.");
        }
        StringBuilder clearText = new StringBuilder();
        for (String chunk : chunks) {
            byte[] byteChunk = hexToByteArray(chunk);
            clearText.append(new String(pkCipher.doFinal(byteChunk), "UTF-8"));
        }
        return clearText.toString();
    } catch (NumberFormatException e) {
        throw new SecurityException(
                "The encrypted information is corrupted or incomplete. Please make sure someone is not trying to intercept or modify encrypted message.",
                e);
    } catch (IOException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (NoSuchPaddingException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (InvalidKeySpecException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (InvalidKeyException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (NoSuchProviderException e) {
        throw new SecurityException(
                "Failed to find encryption provider. Please use Java version with cryptography support.", e);
    } catch (IllegalBlockSizeException e) {
        throw new SecurityException("Failed to decrypt message. It might have been corrupted during transport.",
                e);
    } catch (BadPaddingException e) {
        throw new SecurityException("Failed to decrypt message. It might have been corrupted during transport.",
                e);
    }

}

From source file:com.sun.socialsite.business.impl.JPAPermissionManagerImpl.java

/**
 * {@inheritDoc}/*from   w  ww  .  j ava2 s .c o  m*/
 */
public void checkPermission(Permission requiredPermission, SecurityToken token) throws SocialSiteException {
    Permissions grantedPermissions = getPermissions(token);
    log.debug("requiredPermission=" + requiredPermission);
    log.debug("grantedPermissions=" + grantedPermissions);
    if (grantedPermissions.implies(requiredPermission) == false) {
        throw new SecurityException("Access Denied");
    }
}

From source file:org.dhara.CustomUserService.java

@Override
public User getAuthenticatedUser() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication != null && authentication.getPrincipal() instanceof User) {
        return (User) authentication.getPrincipal();
    } else {//w ww  .  j a  v  a2s . co m
        throw new SecurityException("Could not get the authenticated user!");
    }
}

From source file:org.sakaiproject.adminsiteperms.service.SitePermsService.java

/**
 * Set permissions (perms) in a set of site types (types) for a set of roles (roles)
 * /*from w w  w.j ava  2  s  . co  m*/
 * @param perms a list of permission keys
 * @param types a list of site types (course/project/workspace/etc.)
 * @param roles a list of site roles
 * @param add if true then add the permissions, if false then remove them
 */
public void setSiteRolePerms(final String[] perms, final String[] types, final String[] roles,
        final boolean add) {
    if (!securityService.isSuperUser()) {
        throw new SecurityException("setSiteRolePerms is only usable by super users");
    }
    if (isLockedForUpdates()) {
        throw new IllegalStateException("Cannot start new perms update, one is already in progress");
    }
    // get the configurable values
    pauseTimeMS = serverConfigurationService.getConfig("site.adminperms.pause.ms", pauseTimeMS);
    int maxUpdateTimeS = serverConfigurationService.getConfig("site.adminperms.maxrun.secs",
            DEFAULT_MAX_UPDATE_TIME_SECS);
    maxUpdateTimeMS = 1000l * maxUpdateTimeS; // covert to milliseconds
    sitesUntilPause = serverConfigurationService.getConfig("site.adminperms.sitesuntilpause", sitesUntilPause);
    // get the current state
    final User currentUser = userDirectoryService.getCurrentUser();
    final Session currentSession = sessionManager.getCurrentSession();
    // run this in a new thread
    Runnable backgroundRunner = new Runnable() {
        public void run() {
            try {
                initiateSitePermsThread(currentUser, currentSession, perms, types, roles, add);
            } catch (IllegalStateException e) {
                throw e; // rethrow this back out
            } catch (Exception e) {
                log.error("SitePerms background perms runner thread died: " + e, e);
            }
        }
    };
    Thread bgThread = new Thread(backgroundRunner);
    bgThread.setDaemon(true); // important, otherwise JVM cannot exit
    bgThread.start();
}

From source file:org.mule.module.launcher.DefaultMuleDeployer.java

public Application installFromAppDir(String packedMuleAppFileName) throws IOException {
    final File appsDir = MuleContainerBootstrapUtils.getMuleAppsDir();
    File appFile = new File(appsDir, packedMuleAppFileName);

    // basic security measure: outside apps dir use installFrom(url) and go through any
    // restrictions applied to it
    if (!appFile.getParentFile().equals(appsDir)) {
        throw new SecurityException(
                "installFromAppDir() can only deploy from $MULE_HOME/apps. Use installFrom(url) instead.");
    }/*from   ww w. ja va2  s  .c  o m*/

    return installFrom(appFile.toURL());
}

From source file:be.agiv.security.handler.WSSecurityHandler.java

private void handleInboundMessage(SOAPMessageContext context) throws WSSecurityException {
    LOG.debug("checking WS-Security header");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    WSSecurityEngine secEngine = new WSSecurityEngine();
    List<WSSecurityEngineResult> results = secEngine.processSecurityHeader(soapPart, null, null, null);
    if (null == results) {
        throw new SecurityException("no WS-Security results");
    }//from ww w.j  av  a  2 s.  co  m

    WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.TS);
    if (null == actionResult) {
        throw new SecurityException("no WS-Security timestamp result");
    }

    Timestamp receivedTimestamp = (Timestamp) actionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP);
    if (null == receivedTimestamp) {
        throw new SecurityException("no WS-Security timestamp");
    }

    LOG.debug("WS-Security timestamp created: " + receivedTimestamp.getCreated());
    LOG.debug("WS-Security timestamp expires: " + receivedTimestamp.getExpires());
}

From source file:eu.forgestore.ws.util.ShiroBasicAuthInterceptor.java

public void handleMessage(Message message) throws Fault {

    Subject currentUser = SecurityUtils.getSubject();
    if (currentUser != null) {
        logger.info("handleMessage currentUser = " + currentUser.toString());
        logger.info("currentUser.getPrincipal() = " + currentUser.getPrincipal());
        logger.info("SecurityUtils.getSubject().getSession() = " + currentUser.getSession().getId());
        logger.info("currentUser.getSession().getAttribute(  aKey ) = "
                + currentUser.getSession().getAttribute("aKey"));
        logger.info("message.getId() = " + message.getId());

        // Here We are getting session from Message
        HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
        HttpSession session = request.getSession();

        logger.info("HttpSession session.getId() = " + session.getId());

        if (currentUser.getPrincipal() != null) {
            logger.info("User [" + currentUser.getPrincipal()
                    + "] IS ALREADY logged in successfully. =========================");

            if (currentUser.isAuthenticated()) {
                logger.info("User [" + currentUser.getPrincipal()
                        + "] IS isAuthenticated and logged in successfully. =========================");
                return;
            }/*  w w  w  . java2s .com*/

            if (currentUser.isRemembered()) {
                logger.info("User [" + currentUser.getPrincipal()
                        + "] IS REMEMBERED and logged in successfully. =========================");
                return;
            }
        }
    }

    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
    if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
        String name = null;
        if (policy != null) {
            name = policy.getUserName();
        }
        String error = "No user credentials are available";
        logger.warn(error + " " + "for name: " + name);
        throw new SecurityException(error);
    }

    try {

        UsernameToken token = convertPolicyToToken(policy);

        String s = validator.validate(token);
        //
        // Create a Principal/SecurityContext
        //bale principal apo to validator
        //         Principal p = null;
        //         if (s!=null) {
        //            p = new SimplePrincipal( s );
        //         }
        //
        //         message.put(SecurityContext.class, createSecurityContext(p));
        currentUser.getSession().setAttribute("aKey", UUID.randomUUID().toString());

    } catch (Exception ex) {
        throw new Fault(ex);
    }
}

From source file:be.fedict.hsm.ws.impl.WSSecuritySOAPHandler.java

private void handleInboundMessage(SOAPMessageContext context) throws WSSecurityException, SOAPException {
    LOG.debug("checking WS-Security header");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    WSSecurityEngine secEngine = new WSSecurityEngine();
    Crypto crypto = new WSSecurityCrypto();
    WSSConfig wssConfig = new WSSConfig();
    wssConfig.setWsiBSPCompliant(true);//from   w  w w.  j  a  v  a2s  . c om
    secEngine.setWssConfig(wssConfig);
    List<WSSecurityEngineResult> results = secEngine.processSecurityHeader(soapPart, null, null, crypto);
    if (null == results) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security results");
    }

    WSSecurityEngineResult timeStampActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.TS);
    if (null == timeStampActionResult) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security timestamp result");
    }

    Timestamp receivedTimestamp = (Timestamp) timeStampActionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP);
    if (null == receivedTimestamp) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security timestamp");
    }

    LOG.debug("WS-Security timestamp created: " + receivedTimestamp.getCreated());
    LOG.debug("WS-Security timestamp expires: " + receivedTimestamp.getExpires());
    String timeStampIdRef = "#" + receivedTimestamp.getID();

    WSSecurityEngineResult bstActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.BST);
    if (null == bstActionResult) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security BinarySecurityToken");
    }
    BinarySecurity binarySecurityToken = (BinarySecurity) bstActionResult
            .get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);

    WSSecurityEngineResult signActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.SIGN);
    if (null == signActionResult) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no valid XML signature");
    }
    String signatureMethod = (String) signActionResult.get(WSSecurityEngineResult.TAG_SIGNATURE_METHOD);
    LOG.debug("signature method: " + signatureMethod);
    if (false == "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256".equals(signatureMethod)) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("signature algo should be RSA-SHA256");
    }
    X509Certificate certificate = (X509Certificate) signActionResult
            .get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
    LOG.debug("certificate subject: " + certificate.getSubjectX500Principal());
    List<WSDataRef> wsDataRefs = (List<WSDataRef>) signActionResult
            .get(WSSecurityEngineResult.TAG_DATA_REF_URIS);

    SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
    SOAPBody soapBody = soapEnvelope.getBody();
    String bodyIdRef = "#" + soapBody.getAttributeNS(WSU_NAMESPACE, "Id");
    String bstIdRef = "#" + binarySecurityToken.getID();

    boolean timestampDigested = false;
    boolean bodyDigested = false;
    boolean tokenDigested = false;
    for (WSDataRef wsDataRef : wsDataRefs) {
        String wsuId = wsDataRef.getWsuId();
        LOG.debug("signed wsu:Id: " + wsuId);
        LOG.debug("digest algorithm: " + wsDataRef.getDigestAlgorithm());
        if (false == "http://www.w3.org/2001/04/xmlenc#sha256".equals(wsDataRef.getDigestAlgorithm())) {
            this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
            throw new SecurityException("digest algorithm should be SHA256");
        }
        if (timeStampIdRef.equals(wsuId)) {
            timestampDigested = true;
        } else if (bodyIdRef.equals(wsuId)) {
            bodyDigested = true;
        } else if (bstIdRef.equals(wsuId)) {
            tokenDigested = true;
        }
    }
    if (false == timestampDigested) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
        throw new SecurityException("timestamp not digested");
    }
    if (false == bodyDigested) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
        throw new SecurityException("SOAP Body not digested");
    }
    if (false == tokenDigested) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
        throw new SecurityException("BinarySecurityToken not digested");
    }

    context.put(X509_ATTRIBUTE, certificate);
}

From source file:org.nebulaframework.deployment.classloading.AbstractNebulaClassLoader.java

/**
 * Checks a given class name against a pre-defined set of
 * prohibited packages and classes. If identified as a 
 * prohibited class, this method throws {@link SecurityException}.
 * <p>/*from   w  w  w  .  j  ava2 s .c  om*/
 * This method is used by Nebula Custom ClassLoaders to disallow
 * remote code access to several important classes of the
 * framework, which may lead to security issues otherwise.
 * 
 * @param name name of class
 * @throws SecurityException if class is prohibited
 */
protected void checkProhibited(String name) throws SecurityException {

    // Check for Prohibited Packages
    for (String pkg : PROHIBITED_PACKAGES) {
        if (name.startsWith(pkg)) {
            log.warn("Attempted to access prohibited package : " + pkg);
            throw new SecurityException("Package " + pkg + " is not accessible");
        }
    }

    // Check for Prohibited Classes
    for (String cls : PROHIBITED_CLASSES) {
        if (name.equals(cls)) {
            log.warn("Attempted to access prohibited class : " + name);
            throw new SecurityException("Class " + cls + " is not accessible");
        }
    }
}

From source file:androidx.core.app.NotificationCompatSideChannelService.java

void checkPermission(int callingUid, String packageName) {
    for (String validPackage : getPackageManager().getPackagesForUid(callingUid)) {
        if (validPackage.equals(packageName)) {
            return;
        }/*from ww  w  . j a  v a  2s .c  om*/
    }
    throw new SecurityException("NotificationSideChannelService: Uid " + callingUid
            + " is not authorized for package " + packageName);
}