Example usage for java.lang SecurityException getMessage

List of usage examples for java.lang SecurityException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.apache.directory.fortress.core.AdminMgrConsole.java

/**
 * Description of the Method/* w  ww.  j  av a2 s  .  co m*/
 */
protected void updateUser() {
    User ue = new User();

    try {
        ReaderUtil.clearScreen();
        System.out.println("Enter userId");
        ue.setUserId(ReaderUtil.readLn());
        System.out.println("Enter pw");
        ue.setPassword(ReaderUtil.readLn().toCharArray());

        System.out.println("Do you want to test Admin User update - Y or N");
        String choice = ReaderUtil.readLn();
        if (choice != null && choice.equalsIgnoreCase("Y")) {
            AccessMgr accessMgr = AccessMgrFactory.createInstance(GlobalIds.HOME);
            User admin = new User();
            System.out.println("Enter userId");
            admin.setUserId(ReaderUtil.readLn());
            System.out.println("Enter pw");
            admin.setPassword(ReaderUtil.readLn().toCharArray());
            Session session = accessMgr.createSession(admin, false);
            am.setAdmin(session);
        }

        System.out.println("Enter user's description field");
        ue.setDescription(ReaderUtil.readLn());
        //System.out.println("Enter User's common name");
        //ue.cn = ReaderUtil.readLn();
        //System.out.println("Enter User's surname");
        //ue.sn = ReaderUtil.readLn();
        System.out.println("Enter organization unit, blank for default");
        ue.setOu(ReaderUtil.readLn());

        System.out.println("Do you want to set temporal constraints on User - Y or N");
        choice = ReaderUtil.readLn();
        if (choice != null && choice.equalsIgnoreCase("Y")) {
            enterTemporal(ue);
        }

        System.out.println("Enter prop key (or NULL to skip):");
        String key = ReaderUtil.readLn();
        for (int i = 0; key != null && key.length() > 0; i++) {
            System.out.println("Enter prop val:");
            String val = ReaderUtil.readLn();
            ue.addProperty(key, val);
            System.out.println("Enter next prop key (or NULL if done entering properties)");
            key = ReaderUtil.readLn();
        }
        System.out.println("Enter OpenLDAP password policy name or NULL to skip");
        String plcyNm = ReaderUtil.readLn();
        if (plcyNm != null && plcyNm.length() > 0)
            ue.setPwPolicy(plcyNm);

        am.updateUser(ue);
        System.out.println("userId [" + ue.getUserId() + "]");
        System.out.println("internalId [" + ue.getInternalId() + "]");
        System.out.println("user description [" + ue.getDescription() + "]");
        //System.out.println("user common name [" + ue.cn + "]");
        //System.out.println("user surname [" + ue.sn + "]");
        System.out.println("organizational unit [" + ue.getOu() + "]");
        System.out.println("has been updated");
        System.out.println("ENTER to continue");
    } catch (SecurityException e) {
        LOG.error("updateUser caught SecurityException rc=" + e.getErrorId() + ", msg=" + e.getMessage(), e);
    }
    ReaderUtil.readChar();
}

From source file:org.apache.directory.fortress.core.AdminMgrConsole.java

void addPermOperation() {
    Permission pe = new Permission();
    try {//from w  w w .j  a va  2 s  . c  o  m
        ReaderUtil.clearScreen();
        System.out.println("Enter perm object name:");
        pe.setObjName(ReaderUtil.readLn());
        System.out.println("Enter perm object id (or NULL to skip):");
        String oid = ReaderUtil.readLn();
        if (oid != null && oid.length() > 0)
            pe.setObjId(oid);
        System.out.println("Enter Perm operation name:");
        pe.setOpName(ReaderUtil.readLn());
        //System.out.println("Enter Perm abstract name:");
        //pe.setAbstractName(ReaderUtil.readLn());

        System.out.println("Enter role name (or NULL to skip):");
        String val = ReaderUtil.readLn();
        for (int i = 0; val != null && val.length() > 0; i++) {
            pe.setRole(val);
            System.out.println("Enter next role name (or NULL if done entering roles):");
            val = ReaderUtil.readLn();
        }
        System.out.println("Enter user (or NULL to skip):");
        val = ReaderUtil.readLn();
        for (int i = 0; val != null && val.length() > 0; i++) {
            pe.setUser(val);
            System.out.println("Enter next user (or NULL if done entering users):");
            val = ReaderUtil.readLn();
        }
        System.out.println("Enter prop key (or NULL to skip):");
        String key = ReaderUtil.readLn();
        for (int i = 0; key != null && key.length() > 0; i++) {
            System.out.println("Enter prop val:");
            val = ReaderUtil.readLn();
            pe.addProperty(key, val);
            System.out.println("Enter next prop key (or NULL if done entering properties)");
            key = ReaderUtil.readLn();
        }

        pe = am.addPermission(pe);
        System.out.println("perm object name [" + pe.getObjName() + "]");
        System.out.println("perm operation name [" + pe.getOpName() + "]");
        System.out.println("perm abstract name [" + pe.getAbstractName() + "]");
        System.out.println("internalId [" + pe.getInternalId() + "]");
        if (pe.getUsers() != null && pe.getUsers().size() > 0) {
            int ctr = 0;
            for (String user : pe.getUsers()) {
                System.out.println("user[" + ctr++ + "]=" + user);
            }
        }
        if (pe.getRoles() != null && pe.getRoles().size() > 0) {
            int ctr = 0;
            for (String role : pe.getRoles()) {
                System.out.println("name[" + ctr++ + "]=" + role);
            }
        }
        if (pe.getProperties() != null && pe.getProperties().size() > 0) {
            int ctr = 0;
            for (Enumeration e = pe.getProperties().propertyNames(); e.hasMoreElements();) {
                key = (String) e.nextElement();
                val = pe.getProperty(key);
                System.out.println("prop key[" + ctr + "]=" + key);
                System.out.println("prop value[" + ctr++ + "]=" + val);
            }
        }
        System.out.println("has been added");
        System.out.println("ENTER to continue");
    } catch (SecurityException e) {
        LOG.error("addPermOperation caught SecurityException rc=" + e.getErrorId() + ", msg=" + e.getMessage(),
                e);
    }
    ReaderUtil.readChar();
}

From source file:org.apache.accumulo.core.conf.Property.java

private <T extends Annotation> boolean hasAnnotation(Class<T> annotationType) {
    Logger log = LoggerFactory.getLogger(getClass());
    try {/*from   w w w.  ja v a2 s .  com*/
        for (Annotation a : getClass().getField(name()).getAnnotations())
            if (annotationType.isInstance(a))
                return true;
    } catch (SecurityException e) {
        log.error("{}", e.getMessage(), e);
    } catch (NoSuchFieldException e) {
        log.error("{}", e.getMessage(), e);
    }
    return false;
}

From source file:org.apache.directory.fortress.core.AdminMgrConsole.java

/**
 * Adds a feature to the User attribute of the AdminMgrConsole object
 *//*from   w ww.jav  a 2 s . c  o m*/
void addUser() {
    User ue = new User();

    try {
        ReaderUtil.clearScreen();
        System.out.println("Enter userId:");
        ue.setUserId(ReaderUtil.readLn());
        System.out.println("Enter user's common name (cn):");
        String cn = ReaderUtil.readLn();
        System.out.println("Enter user's surname (sn):");
        String sn = ReaderUtil.readLn();
        ue.setSn(sn);
        ue.setCn(cn);
        System.out.println("Enter pw");
        ue.setPassword(ReaderUtil.readLn().toCharArray());
        System.out.println("Enter User's description field");
        ue.setDescription(ReaderUtil.readLn());
        System.out.println("Enter organization unit, blank for default");
        ue.setOu(ReaderUtil.readLn());

        System.out.println("Do you want to set temporal constraints on User - Y or N");
        String choice = ReaderUtil.readLn();
        if (choice != null && choice.equalsIgnoreCase("Y")) {
            enterTemporal(ue);
        }

        System.out.println("Do you want to set posix account attributes on User - Y or N");
        choice = ReaderUtil.readLn();
        if (choice != null && choice.equalsIgnoreCase("Y")) {
            enterPosixAccount(ue);
        }

        System.out.println("Enter Role name (or NULL to skip):");
        String val = ReaderUtil.readLn();
        for (int i = 0; val != null && val.length() > 0; i++) {
            UserRole userRole = new UserRole();
            userRole.setName(val);
            userRole.setUserId(ue.getUserId());
            ue.setRole(userRole);
            System.out.println("Do you want to set temporal constraints on User - Y or N");
            choice = ReaderUtil.readLn();
            if (choice != null && choice.equalsIgnoreCase("Y")) {
                enterTemporal(userRole);
            }

            System.out.println("Enter next name (or NULL if done entering roles):");
            val = ReaderUtil.readLn();
        }

        System.out.println("Enter prop key (or NULL to skip):");
        String key = ReaderUtil.readLn();
        for (int i = 0; key != null && key.length() > 0; i++) {
            System.out.println("Enter prop val:");
            val = ReaderUtil.readLn();
            ue.addProperty(key, val);
            System.out.println("Enter next prop key (or NULL if done entering properties)");
            key = ReaderUtil.readLn();
        }

        System.out.println("Enter password policy (or NULL to skip):");
        String policy = ReaderUtil.readLn();
        if (StringUtils.isNotEmpty(policy)) {
            ue.setPwPolicy(policy);
        }
        /*
                    ue.setAddress(new Address());
                    ue.getAddress().setAddress("123 Test Ln");
                    ue.getAddress().setAddress("Suite 1");
                    ue.getAddress().setAddress("c/o resident");
                    ue.getAddress().setCity("TestCity");
                    ue.getAddress().setCountry("US");
                    ue.getAddress().setPostalCode("72113");
                    ue.getAddress().setState("AR");
                    ue.setPhone("111-222-3333");
                    ue.setPhone("222-222-3333");
                    ue.setMobile("333-222-3333");
                    ue.setMobile("444-222-3333");
        */
        User ue2 = am.addUser(ue);
        if (CollectionUtils.isNotEmpty(ue.getRoles())) {
            for (UserRole uRole : ue.getRoles()) {
                am.assignUser(uRole);
            }
        }
        System.out.println("userId [" + ue2.getUserId() + "]");
        System.out.println("internalId [" + ue2.getInternalId() + "]");
        System.out.println("user description [" + ue2.getDescription() + "]");
        System.out.println("user common name [" + ue2.getCn() + "]");
        System.out.println("user surname [" + ue2.getSn() + "]");
        System.out.println("organizational unit [" + ue2.getOu() + "]");
        System.out.println("has been added");
        System.out.println("ENTER to continue");
    } catch (SecurityException e) {
        LOG.error("addUser caught SecurityException rc=" + e.getErrorId() + ", msg=" + e.getMessage(), e);
    } catch (Exception e) {
        LOG.error("addUser caught Exception=" + e);
        e.printStackTrace();
    }
    ReaderUtil.readChar();
}

From source file:be.fedict.eid.applet.service.impl.handler.AuthenticationDataMessageHandler.java

public Object handleMessage(AuthenticationDataMessage message, Map<String, String> httpHeaders,
        HttpServletRequest request, HttpSession session) throws ServletException {
    LOG.debug("authentication data message received");

    if (null == message.authnCert) {
        /*//from   w w w  .ja va 2s  . c om
         * Can be the case for future (Kids) eID cards that have some
         * certificates missing.
         */
        String msg = "authentication certificate not present";
        LOG.warn(msg);
        throw new ServletException(msg);
    }
    byte[] signatureValue = message.signatureValue;
    LOG.debug("authn signing certificate subject: " + message.authnCert.getSubjectX500Principal());
    PublicKey signingKey = message.authnCert.getPublicKey();

    if (this.sessionIdChannelBinding) {
        checkSessionIdChannelBinding(message, request);
        if (null == this.serverCertificate) {
            LOG.warn("adviced to use in combination with server certificate channel binding");
        }
    }

    ChannelBindingService channelBindingService = this.channelBindingServiceLocator.locateService();
    if (null != this.serverCertificate || null != channelBindingService) {
        LOG.debug("using server certificate channel binding");
    }

    if (false == this.sessionIdChannelBinding && null == this.serverCertificate
            && null == channelBindingService) {
        LOG.warn("not using any secure channel binding");
    }

    byte[] challenge;
    try {
        challenge = AuthenticationChallenge.getAuthnChallenge(session, this.maxMaturity);
    } catch (SecurityException e) {
        AuditService auditService = this.auditServiceLocator.locateService();
        if (null != auditService) {
            String remoteAddress = request.getRemoteAddr();
            auditService.authenticationError(remoteAddress, message.authnCert);
        }
        throw new ServletException("security error: " + e.getMessage(), e);
    }

    byte[] serverCertificateClientPOV = null;
    try {
        if (null != message.serverCertificate) {
            serverCertificateClientPOV = message.serverCertificate.getEncoded();
        }
    } catch (CertificateEncodingException e) {
        throw new ServletException("server cert decoding error: " + e.getMessage(), e);
    }
    /*
     * We validate the authentication contract using the client-side
     * communicated server SSL certificate in case of secure channel
     * binding.
     */
    AuthenticationContract authenticationContract = new AuthenticationContract(message.saltValue, this.hostname,
            this.inetAddress, message.sessionId, serverCertificateClientPOV, challenge);
    byte[] toBeSigned;
    try {
        toBeSigned = authenticationContract.calculateToBeSigned();
    } catch (IOException e) {
        throw new ServletException("IO error: " + e.getMessage(), e);
    }

    try {
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initVerify(signingKey);
        signature.update(toBeSigned);
        boolean result = signature.verify(signatureValue);
        if (false == result) {
            AuditService auditService = this.auditServiceLocator.locateService();
            if (null != auditService) {
                String remoteAddress = request.getRemoteAddr();
                auditService.authenticationError(remoteAddress, message.authnCert);
            }
            throw new SecurityException("authn signature incorrect");
        }
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException("algo error");
    } catch (InvalidKeyException e) {
        throw new SecurityException("authn key error");
    } catch (SignatureException e) {
        throw new SecurityException("signature error");
    }

    RequestContext requestContext = new RequestContext(session);
    String transactionMessage = requestContext.getTransactionMessage();
    if (null != transactionMessage) {
        LOG.debug("verifying TransactionMessage signature");
        byte[] transactionMessageSignature = message.transactionMessageSignature;
        if (null == transactionMessageSignature) {
            throw new SecurityException("missing TransactionMessage signature");
        }
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, signingKey);
            byte[] signatureDigestInfoValue = cipher.doFinal(transactionMessageSignature);
            ASN1InputStream aIn = new ASN1InputStream(signatureDigestInfoValue);
            DigestInfo signatureDigestInfo = new DigestInfo((ASN1Sequence) aIn.readObject());
            if (false == PLAIN_TEXT_DIGEST_ALGO_OID
                    .equals(signatureDigestInfo.getAlgorithmId().getObjectId().getId())) {
                throw new SecurityException("TransactionMessage signature algo OID incorrect");
            }
            if (false == Arrays.equals(transactionMessage.getBytes(), signatureDigestInfo.getDigest())) {
                throw new SecurityException("signed TransactionMessage incorrect");
            }
            LOG.debug("TransactionMessage signature validated");
        } catch (Exception e) {
            LOG.error("error verifying TransactionMessage signature", e);
            AuditService auditService = this.auditServiceLocator.locateService();
            if (null != auditService) {
                String remoteAddress = request.getRemoteAddr();
                auditService.authenticationError(remoteAddress, message.authnCert);
            }
            throw new SecurityException("error verifying TransactionMessage signature: " + e.getMessage());
        }
    }

    /*
     * Secure channel binding verification.
     */
    if (null != channelBindingService) {
        X509Certificate serverCertificate = channelBindingService.getServerCertificate();
        if (null == serverCertificate) {
            LOG.warn("could not verify secure channel binding as the server does not know its identity yet");
        } else {
            if (false == serverCertificate.equals(message.serverCertificate)) {
                AuditService auditService = this.auditServiceLocator.locateService();
                if (null != auditService) {
                    String remoteAddress = request.getRemoteAddr();
                    auditService.authenticationError(remoteAddress, message.authnCert);
                }
                throw new SecurityException("secure channel binding identity mismatch");
            }
            LOG.debug("secure channel binding verified");
        }
    } else {
        if (null != this.serverCertificate) {
            if (false == this.serverCertificate.equals(message.serverCertificate)) {
                AuditService auditService = this.auditServiceLocator.locateService();
                if (null != auditService) {
                    String remoteAddress = request.getRemoteAddr();
                    auditService.authenticationError(remoteAddress, message.authnCert);
                }
                throw new SecurityException("secure channel binding identity mismatch");
            }
            LOG.debug("secure channel binding verified");
        }
    }

    AuthenticationService authenticationService = this.authenticationServiceLocator.locateService();
    List<X509Certificate> certificateChain = new LinkedList<X509Certificate>();
    certificateChain.add(message.authnCert);
    certificateChain.add(message.citizenCaCert);
    certificateChain.add(message.rootCaCert);
    certificateChain.add(message.rrnCertificate);
    try {
        authenticationService.setHttpSessionObject(request.getSession());
        authenticationService.validateCertificateChain(certificateChain);
    } catch (ExpiredCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
    } catch (RevokedCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
    } catch (TrustCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
    } catch (CertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE);
    } catch (Exception e) {
        /*
         * We don't want to depend on the full JavaEE profile in this
         * artifact.
         */
        if ("javax.ejb.EJBException".equals(e.getClass().getName())) {
            Exception exception;
            try {
                Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException",
                        new Class[] {});
                exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {});
            } catch (Exception e2) {
                LOG.debug("error: " + e.getMessage(), e);
                throw new SecurityException("error retrieving the root cause: " + e2.getMessage());
            }
            if (exception instanceof ExpiredCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
            }
            if (exception instanceof RevokedCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
            }
            if (exception instanceof TrustCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
            }
            if (exception instanceof CertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE);
            }
        }
        throw new SecurityException("authn service error: " + e.getMessage());
    }

    String userId = UserIdentifierUtil.getUserId(message.authnCert);
    LOG.info("authenticated: " + userId + " @ " + request.getRemoteAddr());
    if (null != this.nrcidSecret) {
        userId = UserIdentifierUtil.getNonReversibleCitizenIdentifier(userId, this.nrcidOrgId, this.nrcidAppId,
                this.nrcidSecret);
    }
    /*
     * Some people state that you cannot use the national register number
     * without hashing. Problem is that hashing introduces hash collision
     * problems. The probability is very low, but what if it's your leg
     * they're cutting of because of a patient mismatch based on the SHA1 of
     * your national register number?
     */

    /*
     * Push authenticated used Id into the HTTP session.
     */
    session.setAttribute(AUTHENTICATED_USER_IDENTIFIER_SESSION_ATTRIBUTE, userId);

    EIdData eidData = (EIdData) session.getAttribute(IdentityDataMessageHandler.EID_SESSION_ATTRIBUTE);
    if (null == eidData) {
        eidData = new EIdData();
        session.setAttribute(IdentityDataMessageHandler.EID_SESSION_ATTRIBUTE, eidData);
    }
    eidData.identifier = userId;

    AuditService auditService = this.auditServiceLocator.locateService();
    if (null != auditService) {
        auditService.authenticated(userId);
    }

    boolean includeIdentity = requestContext.includeIdentity();
    boolean includeAddress = requestContext.includeAddress();
    boolean includeCertificates = requestContext.includeCertificates();
    boolean includePhoto = requestContext.includePhoto();

    /*
     * Also process the identity data in case it was requested.
     */
    if (includeIdentity) {
        if (null == message.identityData) {
            throw new ServletException("identity data not included while requested");
        }
    }
    if (includeAddress) {
        if (null == message.addressData) {
            throw new ServletException("address data not included while requested");
        }
    }
    if (includePhoto) {
        if (null == message.photoData) {
            throw new ServletException("photo data not included while requested");
        }
    }
    IdentityIntegrityService identityIntegrityService = this.identityIntegrityServiceLocator.locateService();
    if (null != identityIntegrityService) {
        if (null == message.rrnCertificate) {
            throw new ServletException("national registry certificate not included while requested");
        }
        List<X509Certificate> rrnCertificateChain = new LinkedList<X509Certificate>();
        rrnCertificateChain.add(message.rrnCertificate);
        rrnCertificateChain.add(message.rootCaCert);

        try {
            identityIntegrityService.checkNationalRegistrationCertificate(rrnCertificateChain);
        } catch (ExpiredCertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
        } catch (RevokedCertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
        } catch (TrustCertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
        } catch (CertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE);
        } catch (Exception e) {
            if ("javax.ejb.EJBException".equals(e.getClass().getName())) {
                Exception exception;
                try {
                    Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException",
                            new Class[] {});
                    exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {});
                } catch (Exception e2) {
                    LOG.debug("error: " + e.getMessage(), e);
                    throw new SecurityException("error retrieving the root cause: " + e2.getMessage());
                }
                if (exception instanceof ExpiredCertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
                }
                if (exception instanceof RevokedCertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
                }
                if (exception instanceof TrustCertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
                }
                if (exception instanceof CertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE);
                }
            }
            throw new SecurityException("error checking the NRN certificate: " + e.getMessage(), e);
        }

        PublicKey rrnPublicKey = message.rrnCertificate.getPublicKey();
        if (includeIdentity) {
            if (null == message.identitySignatureData) {
                throw new ServletException("identity signature data not included while requested");
            }
            verifySignature(message.rrnCertificate.getSigAlgName(), message.identitySignatureData, rrnPublicKey,
                    request, message.identityData);
        }
        if (includeAddress) {
            if (null == message.addressSignatureData) {
                throw new ServletException("address signature data not included while requested");
            }
            byte[] addressFile = trimRight(message.addressData);
            verifySignature(message.rrnCertificate.getSigAlgName(), message.addressSignatureData, rrnPublicKey,
                    request, addressFile, message.identitySignatureData);
        }
    }
    if (includeIdentity) {
        Identity identity = TlvParser.parse(message.identityData, Identity.class);
        if (false == UserIdentifierUtil.getUserId(message.authnCert).equals(identity.nationalNumber)) {
            throw new ServletException("national number mismatch");
        }
        session.setAttribute(IdentityDataMessageHandler.IDENTITY_SESSION_ATTRIBUTE, identity);
        eidData.identity = identity;
        auditService = this.auditServiceLocator.locateService();
        if (null != auditService) {
            auditService.identified(identity.nationalNumber);
        }
    }
    if (includeAddress) {
        Address address = TlvParser.parse(message.addressData, Address.class);
        session.setAttribute(IdentityDataMessageHandler.ADDRESS_SESSION_ATTRIBUTE, address);
        eidData.address = address;
    }
    if (includePhoto) {
        if (includeIdentity) {
            byte[] expectedPhotoDigest = eidData.identity.photoDigest;
            byte[] actualPhotoDigest = digestPhoto(getDigestAlgo(expectedPhotoDigest.length),
                    message.photoData);
            if (false == Arrays.equals(expectedPhotoDigest, actualPhotoDigest)) {
                throw new ServletException("photo digest incorrect");
            }
        }
        session.setAttribute(IdentityDataMessageHandler.PHOTO_SESSION_ATTRIBUTE, message.photoData);
        eidData.photo = message.photoData;
    }
    if (includeCertificates) {
        if (includeIdentity) {
            eidData.certs = new EIdCertsData();
            eidData.certs.authn = message.authnCert;
            eidData.certs.ca = message.citizenCaCert;
            eidData.certs.root = message.rootCaCert;
            eidData.certs.sign = message.signCert;
        }
        session.setAttribute(IdentityDataMessageHandler.AUTHN_CERT_SESSION_ATTRIBUTE, message.authnCert);
        session.setAttribute(IdentityDataMessageHandler.CA_CERT_SESSION_ATTRIBUTE, message.citizenCaCert);
        session.setAttribute(IdentityDataMessageHandler.ROOT_CERT_SESSION_ATTRIBTUE, message.rootCaCert);
        session.setAttribute(IdentityDataMessageHandler.SIGN_CERT_SESSION_ATTRIBUTE, message.signCert);
    }

    if (this.includeDataFiles) {
        session.setAttribute(IdentityDataMessageHandler.EID_DATA_IDENTITY_SESSION_ATTRIBUTE,
                message.identityData);
        session.setAttribute(IdentityDataMessageHandler.EID_DATA_ADDRESS_SESSION_ATTRIBUTE,
                message.addressData);
    }

    AuthenticationSignatureService authenticationSignatureService = this.authenticationSignatureServiceLocator
            .locateService();
    if (null != authenticationSignatureService) {
        List<X509Certificate> authnCertificateChain;
        if (null != message.authnCert) {
            authnCertificateChain = new LinkedList<X509Certificate>();
            authnCertificateChain.add(message.authnCert);
            authnCertificateChain.add(message.citizenCaCert);
            authnCertificateChain.add(message.rootCaCert);
            authnCertificateChain.add(message.rrnCertificate);
        } else {
            authnCertificateChain = null;
        }
        AuthenticationSignatureContext authenticationSignatureContext = new AuthenticationSignatureContextImpl(
                session);
        PreSignResult preSignResult = authenticationSignatureService.preSign(authnCertificateChain,
                authenticationSignatureContext);
        if (null == preSignResult) {
            return new FinishedMessage();
        }
        boolean logoff = preSignResult.getLogoff();
        byte[] computedDigestValue = preSignResult.getDigestInfo().digestValue;
        String digestAlgo = preSignResult.getDigestInfo().digestAlgo;
        String authnMessage = preSignResult.getDigestInfo().description;
        AuthSignRequestMessage authSignRequestMessage = new AuthSignRequestMessage(computedDigestValue,
                digestAlgo, authnMessage, logoff);
        return authSignRequestMessage;
    }
    return new FinishedMessage();
}

From source file:org.sakaiproject.bbb.tool.entity.BBBMeetingEntityProvider.java

public Object getEntity(EntityReference ref) {
    if (logger.isDebugEnabled())
        logger.debug("getEntity(" + ref.getId() + ")");

    String id = ref.getId();/*w  ww .  ja v  a2s.co m*/
    if (id == null || "".equals(id)) {
        return new BBBMeeting();
    }

    try {
        BBBMeeting meeting = meetingManager.getMeeting(id);

        if (meeting == null) {
            throw new EntityNotFoundException("Meeting not found", ref.getReference());
        }

        // for security reasons, clear passwords and meeting token
        meeting.setAttendeePassword(null);
        meeting.setModeratorPassword(null);

        return meeting;

    } catch (SecurityException se) {
        throw new EntityException(se.getMessage(), ref.getReference(), 400);
    } catch (Exception e) {
        throw new EntityException(e.getMessage(), ref.getReference(), 400);
    }
}

From source file:com.hp.hpl.jena.grddl.impl.GRDDL.java

private Transformer transformerFor(final String url) throws TransformerException {
    if (url.equals("RDF/XML")) {
        return xformFactory().newTransformer();
    } else {/*from   ww  w . j  a  v  a  2  s . c o m*/
        logurl(url);
        try {
            ((GRDDLReaderBase) reader).lastSecurityException = null;
            final Transformer rslt[] = { null };
            // TODO  network and source issues
            final Source src = xsltStreamSource(url);
            runInSandbox(new TERunnable() {
                public void run() throws TransformerException {
                    rslt[0] = xformFactory().newTransformer(src);
                }

            }, true);

            SafeURIResolver safeURIResolver = new SafeURIResolver();
            rslt[0].setURIResolver(safeURIResolver);
            ((Controller) rslt[0]).setUnparsedTextURIResolver(safeURIResolver);

            return rslt[0];

        }
        //         catch (AssertionError e) {
        //            if (e.getMessage().startsWith("Failed to load system function: unparsed-text()"))
        //               throw new GRDDLSecurityException("unparsed-text() not permitted in this implementation");
        //              throw e;
        //         }
        catch (SecurityException e) {
            throw new GRDDLSecurityException(e);
        } catch (TransformerException e) {
            //            if (e.toString().contains("result-document")
            //               || e.toString().contains("disabled")
            //               || e.toString().contains("extension") )
            //               throw new GRDDLSecurityException(e);
            if (((GRDDLReaderBase) reader).lastSecurityException != null)
                throw ((GRDDLReaderBase) reader).lastSecurityException;
            System.err.println("<" + url + "> A.Rethrowing " + e.getMessage());
            throw e;

        } catch (RuntimeException e) {
            System.err.println("<" + url + "> B.Rethrowing " + e.toString() + ":" + e.getMessage());
            throw e;
        }
    }
}

From source file:au.com.onegeek.lambda.core.CommandRunner.java

/**
 * Find the assertion class implementor and invoke the call using reflection.
 * //  www.j av a2  s  .c  o  m
 * @param testCommand
 */
public void runCommand(TestCommand testCommand) {
    String keyword = testCommand.getCommand();
    logger.debug("Looking for method with name: " + testCommand.getCommand());

    // Create Test Case w\
    Object object = null;
    Method method = null;

    // Determine argument types
    Class[] argTypes = new Class[testCommand.getParameters().length];
    int k = 0;
    for (k = 0; k < testCommand.getParameters().length; k++) {

        // Check if there is a number hidden in the args list
        // Currently, although most of the Lambda implementation supports Object params
        // The conversion into a class (JavassistTestBuilderImpl) turns them back into 
        // Strings. 

        // TODO: set locale?
        /* NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
         Number number;
         try {
         number = format.parse((String) testCommand.getParameters()[k]);
         testCommand.getParameters()[k] = number;
                 
         // Looks like it ALWAYS comes out of here as long
         // Apache commons to the rescue? Surely there is a library that does this better
         // TODO: fix this
         if (number.getClass().getSimpleName().equalsIgnoreCase("long")) {
            argTypes[k] = long.class;               
         }
         else if (number.getClass().getSimpleName().equalsIgnoreCase("double")) {
            argTypes[k] = double.class;               
         }
         else if (number.getClass().getSimpleName().equalsIgnoreCase("float")) {
            argTypes[k] = float.class;               
         }
        } catch (Exception e) {
         // TODO Auto-generated catch block
         //e.printStackTrace();
        }*/

        //          if (argTypes[k] == null) {
        argTypes[k] = testCommand.getParameters()[k].getClass();
        //          }
        logger.debug("Argument value: " + testCommand.getParameters()[k]);
        logger.debug("Argument class: " + argTypes[k]);
    }

    logger.info("looking for providers...");

    // Find the implementing class of the method
    for (Object provider : this.lambda.getAssertionProviders()) {
        try {
            logger.info("getting method....");
            method = provider.getClass().getMethod(keyword, argTypes);
            logger.info("got one!");
            object = provider;
        } catch (SecurityException e) {
            logger.debug("Not allowed to call method " + keyword + " from Provider <"
                    + provider.getClass().getName() + "> ");
        } catch (NoSuchMethodException e) {
            for (Object object2 : argTypes) {
                logger.debug("Method: " + keyword + ": Arg type: " + object2);
            }
            logger.debug(
                    "Method: " + keyword + " not found in Provider <" + provider.getClass().getName() + "> ");
        }
    }

    logger.info("Checknig if we found a provider");

    if (object == null) {
        logger.error("cannot find provider of method " + keyword);
        fail("Cannot find a provider of method: '" + keyword + "'");
    } else {
        logger.debug("Found source object for method, object: <" + object.toString() + ">");
    }

    // Invoke method
    Object result = "not set";
    try {
        logger.info("Invoking method '" + keyword + "' on object");
        result = method.invoke(object, testCommand.getParameters());
    } catch (IllegalArgumentException e) {
        fail("Method '" + keyword + "' illegal argument exception: " + e.getMessage());
    } catch (IllegalAccessException e) {
        fail("Method '" + keyword + "' illegal acess exception: " + e.getMessage());
    } catch (InvocationTargetException e) {
        // This is usually a failed Assertion from an AssertionProvider
        logger.debug("InvocationTargetException, usually a failed assertion: ");
        if (logger.isErrorEnabled()) {
            e.printStackTrace();
        }
        fail("Method '" + keyword + "' InvocationTarget exception: " + e.getMessage());

        // TODO: remove\handle this better
        e.printStackTrace();
    } catch (AssertionError e) {
        logger.error("Assertion fail: " + e.getMessage());
    }

    logger.debug("output from reflected method: " + result);
}

From source file:it.evilsocket.dsploit.core.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {
    action what_to_do = (action) intent.getSerializableExtra(ACTION);
    boolean exitForError = true;

    if (what_to_do == null) {
        Logger.error("received null action");
        return;//from w  ww  .  jav  a 2 s . com
    }

    mRunning = true;

    switch (what_to_do) {
    case apk_update:
        mCurrentTask = mApkInfo;
        break;
    case ruby_update:
        mCurrentTask = mRubyInfo;
        break;
    case msf_update:
        mCurrentTask = mMsfInfo;
        break;
    case gems_update:
        mCurrentTask = new ArchiveMetadata();
        break;
    }

    try {
        setupNotification();

        synchronized (mCurrentTask) {
            if (!haveLocalFile())
                downloadFile();
            extract();
            correctModes();
            patchShebang();

            if (what_to_do == action.ruby_update)
                updateRubyGems();
            else if (what_to_do == action.msf_update)
                installGems();
            else if (what_to_do == action.gems_update)
                updateGems();

            if (what_to_do != action.apk_update)
                deleteTemporaryFiles();
        }
        exitForError = false;
        if (what_to_do == action.msf_update)
            System.updateLocalMsfVersion();
        if (what_to_do == action.ruby_update)
            System.updateLocalRubyVersion();
        sendDone(what_to_do);
    } catch (SecurityException e) {
        sendError(R.string.bad_permissions);
        Logger.warning(e.getClass().getName() + ": " + e.getMessage());
    } catch (KeyException e) {
        sendError(R.string.checksum_failed);
        Logger.warning(e.getClass().getName() + ": " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        sendError(R.string.error_occured);
        System.errorLogging(e);
    } catch (CancellationException e) {
        Logger.warning(e.getClass().getName() + ": " + e.getMessage());
    } catch (IOException e) {
        sendError(R.string.error_occured);
        System.errorLogging(e);
    } catch (RuntimeException e) {
        sendError(R.string.error_occured);
        if (e.getClass() == NullPointerException.class)
            System.errorLogging(e);
        else
            Logger.error(e.getClass().getName() + ": " + e.getMessage());
    } catch (InterruptedException e) {
        sendError(R.string.error_occured);
        System.errorLogging(e);
    } finally {
        if (exitForError) {
            clearGemsCache();
            wipe();
        }
        stopSelf();
        mRunning = false;
    }
}

From source file:com.ephesoft.dcma.da.dao.hibernate.BatchInstanceDaoImpl.java

/**
 * Gets the Batch Description from the SER file if available.
 * //from w  w w. ja va  2 s  . c o m
 * @param uncSubfolder {@link String}
 * @return batchDescription {@link String}
 */
private String getBatchDescriptionFromSERFile(final String uncSubfolder, final String batchName) {
    String batchDescription = null;
    FileInputStream fileInputStream = null;
    if (!EphesoftStringUtil.isNullOrEmpty(uncSubfolder)) {
        final String serializedFilePath = EphesoftStringUtil.concatenate(uncSubfolder, File.separator,
                BID_SER_FILE_NAME, SERIALIZATION_EXT);
        final File serializedFile = new File(serializedFilePath);
        if (serializedFile.exists()) {
            try {

                fileInputStream = new FileInputStream(serializedFile);
                batchDescription = SerializationUtils.deserialize(fileInputStream).toString();
                serializedFile.delete();
            } catch (final IOException ioException) {
                log.info(EphesoftStringUtil.concatenate("Error during reading the serialized file. ",
                        ioException.getMessage()));
            } catch (final SerializationException serException) {
                log.error("Error during de-serializing the Batch Description: ", serException.getMessage());
            } catch (final IllegalArgumentException illegalArgumentException) {
                log.error("Error during parsing File Input Stream : ", illegalArgumentException.getMessage());
            } catch (final SecurityException securityException) {
                log.info("Unable to delete serialized file : ", securityException.getMessage());
            } finally {
                try {
                    if (fileInputStream != null) {
                        fileInputStream.close();
                    }
                } catch (final IOException ioException) {
                    if (serializedFile != null) {
                        log.error(EphesoftStringUtil.concatenate("Problem closing stream for file : ",
                                serializedFile.getName(), ioException.getMessage()));
                    }
                }
            }

        } else {
            log.info("Serialised file not found in UNC sub folder. Setting Batch Name as Batch Description.");
            batchDescription = batchName;
        }
    }
    return batchDescription;
}