Example usage for java.lang SecurityException SecurityException

List of usage examples for java.lang SecurityException SecurityException

Introduction

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

Prototype

public SecurityException(Throwable cause) 

Source Link

Document

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

Usage

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

/**
 *
 * @see java.security.SecureClassLoader#getPermissions(
 *     java.security.CodeSource)/*from   w  ww  .ja  v a 2s  . c o m*/
 */
protected PermissionCollection getPermissions(CodeSource codesource) {
    boolean isAcceptable = false;
    if (!CHECKED.containsKey(codesource.getLocation())) {
        Certificate[] certs = codesource.getCertificates();
        if (certs == null || certs.length == 0) {
            JOptionPane.showMessageDialog(null, "The jar at " + codesource.getLocation() + " is not signed!",
                    "Security Error", JOptionPane.ERROR_MESSAGE);
            isAcceptable = false;
        } else {
            isAcceptable = true;
            for (int i = 0; (i < certs.length) && isAcceptable; i++) {
                if (!verifyCertificate((X509Certificate) certs[i])) {
                    isAcceptable = false;
                }
            }
        }
        CHECKED.put(codesource.getLocation(), isAcceptable);
    } else {
        isAcceptable = CHECKED.get(codesource.getLocation());
    }

    Permissions permissions = new Permissions();
    if (isAcceptable) {
        permissions.add(new AllPermission());
        return permissions;
    }
    throw new SecurityException("Access denied to " + codesource.getLocation());
}

From source file:com.glaf.core.security.SecurityUtils.java

/**
 * ??/* w w  w . j av a 2 s  .co m*/
 * 
 * @param ctx
 *            
 * @param envelope
 *            ?
 * @param privateKey
 *            ?
 * @return key 
 */
public static Key openDigitalEnvelope(SecurityContext ctx, String envelope, Key privateKey) {
    try {
        Cipher cipher = Cipher.getInstance(ctx.getAsymmetryAlgorithm(), ctx.getJceProvider());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        envelope = StringTools.replaceIgnoreCase(envelope, " ", "");
        byte[] key = cipher.doFinal(Base64.decodeBase64(envelope));

        SecretKeyFactory skf = SecretKeyFactory.getInstance(ctx.getSymmetryKeyAlgorithm(),
                ctx.getJceProvider());
        DESKeySpec keySpec = new DESKeySpec(key);
        Key symmetryKey = skf.generateSecret(keySpec);

        return symmetryKey;
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}

From source file:edu.umich.flowfence.service.KVSSharedPrefs.java

private void checkRead() {
    checkClosed();/*from w  w w . j a  v  a  2 s  .  c  o m*/
    if (!isReadable) {
        throw new SecurityException("Can't read this SharedPreferences");
    }
}

From source file:org.oscarehr.fax.admin.ManageFaxes.java

public ActionForward viewFax(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {/*w  ww. j  a va2  s.  c o  m*/

    if (!securityInfoManager.hasPrivilege(LoggedInInfo.getLoggedInInfoFromSession(request), "_edoc", "r",
            null)) {
        throw new SecurityException("missing required security object (_edoc)");
    }

    try {
        String doc_no = request.getParameter("jobId");
        String pageNum = request.getParameter("curPage");
        if (pageNum == null) {
            pageNum = "0";
        }
        Integer pn = Integer.parseInt(pageNum);
        log.debug("Document No :" + doc_no);
        LogAction.addLog((String) request.getSession().getAttribute("user"), LogConst.READ,
                LogConst.CON_DOCUMENT, doc_no, request.getRemoteAddr());

        FaxJobDao faxJobDao = SpringUtils.getBean(FaxJobDao.class);
        FaxJob faxJob = faxJobDao.find(Integer.parseInt(doc_no));

        int index;
        String filename;
        if ((index = faxJob.getFile_name().lastIndexOf("/")) > -1) {
            filename = faxJob.getFile_name().substring(index + 1);
        } else {
            filename = faxJob.getFile_name();
        }

        String name = filename + "_" + pn + ".png";
        log.debug("name " + name);

        File outfile = null;

        outfile = hasCacheVersion2(faxJob, pn);
        if (outfile != null) {
            log.debug("got doc from local cache   ");
        } else {
            outfile = createCacheVersion2(faxJob, pn);
            if (outfile != null) {
                log.debug("create new doc  ");
            }
        }
        response.setContentType("image/png");
        ServletOutputStream outs = response.getOutputStream();
        response.setHeader("Content-Disposition", "attachment;filename=" + name);

        BufferedInputStream bfis = null;
        try {
            if (outfile != null) {
                bfis = new BufferedInputStream(new FileInputStream(outfile));
                int data;
                while ((data = bfis.read()) != -1) {
                    outs.write(data);
                    // outs.flush();
                }
            } else {
                log.info("Unable to retrieve content for " + faxJob
                        + ". This may indicate previous upload or save errors...");
            }
        } finally {
            if (bfis != null) {
                bfis.close();
            }
        }

        outs.flush();
        outs.close();
    } catch (java.net.SocketException se) {
        MiscUtils.getLogger().error("Error", se);
    } catch (Exception e) {
        MiscUtils.getLogger().error("Error", e);
    }
    return null;

}

From source file:org.gwtspringhibernate.reference.rlogman.spring.GwtServiceExporter.java

/**
 * This is public so that it can be unit tested easily without HTTP.
 *///  w w w  .  jav a2  s.  co  m
public String processCall(String payload) throws SerializationException {

    // Let subclasses see the serialized request.
    //
    onBeforeRequestDeserialized(payload);

    // Create a stream to deserialize the request.
    //
    ServerSerializationStreamReader streamReader = new ServerSerializationStreamReader(serializableTypeOracle);
    streamReader.prepareToRead(payload);

    // Read the service interface
    //
    String serviceIntfName = streamReader.readString();

    // TODO(mmendez): need to check the signature
    // Verify that this very servlet implements the specified interface
    // name.
    //
    if (!isImplementedRemoteServiceInterface(serviceIntfName)) {
        // Bad payload, possible hack attempt.
        //
        throw new SecurityException("Blocked attempt to access interface '" + serviceIntfName
                + "', which is either not implemented by this servlet or which doesn't extend RemoteService; this is either misconfiguration or a hack attempt");
    }

    // Actually get the service interface, so that we can query its methods.
    //
    Class serviceIntf;
    try {
        serviceIntf = getClassFromName(serviceIntfName);
    } catch (ClassNotFoundException e) {
        throw new SerializationException("Unknown service interface class '" + serviceIntfName + "'", e);
    }

    // Read the method name.
    //
    String methodName = streamReader.readString();

    // Read the number and names of the parameter classes from the stream.
    // We have to do this so that we can find the correct overload of the
    // method.
    //
    int paramCount = streamReader.readInt();
    Class[] paramTypes = new Class[paramCount];
    for (int i = 0; i < paramTypes.length; i++) {
        String paramClassName = streamReader.readString();
        try {
            paramTypes[i] = getClassFromName(paramClassName);
        } catch (ClassNotFoundException e) {
            throw new SerializationException("Unknown parameter " + i + " type '" + paramClassName + "'", e);
        }
    }

    // For security, make sure the method is found in the service interface
    // and not just one that happens to be defined on this class.
    //
    Method serviceIntfMethod = findInterfaceMethod(serviceIntf, methodName, paramTypes, true);

    // If it wasn't found, don't continue.
    //
    if (serviceIntfMethod == null) {
        // Bad payload, possible hack attempt.
        //
        throw new SecurityException("Method '" + methodName + "' (or a particular overload) on interface '"
                + serviceIntfName + "' was not found, this is either misconfiguration or a hack attempt");
    }

    // Deserialize the parameters.
    //
    Object[] args = new Object[paramCount];
    for (int i = 0; i < args.length; i++) {
        args[i] = streamReader.deserializeValue(paramTypes[i]);
    }

    // Make the call via reflection.
    //
    String responsePayload = GENERIC_FAILURE_MSG;
    ServerSerializationStreamWriter streamWriter = new ServerSerializationStreamWriter(serializableTypeOracle);
    Throwable caught = null;
    try {
        Class returnType = serviceIntfMethod.getReturnType();
        /**
         * The method is not invoked from <code>this</code> but from <code>this.proxy</code>;
         * <code>this</code> is the exporter, <code>this.proxy</code> is the actual service
         * implementation
         * @author rlogman@gmail.com
         */
        Object returnVal = serviceIntfMethod.invoke(this.proxy, args);
        responsePayload = createResponse(streamWriter, returnType, returnVal, false);
    } catch (IllegalArgumentException e) {
        caught = e;
    } catch (IllegalAccessException e) {
        caught = e;
    } catch (InvocationTargetException e) {
        // Try to serialize the caught exception if the client is expecting
        // it,
        // otherwise log the exception server-side.
        caught = e;
        Throwable cause = e.getCause();
        if (cause != null) {
            // Update the caught exception to the underlying cause
            caught = cause;
            // Serialize the exception back to the client if it's a declared
            // exception
            if (isExpectedException(serviceIntfMethod, cause)) {
                Class thrownClass = cause.getClass();
                responsePayload = createResponse(streamWriter, thrownClass, cause, true);
                // Don't log the exception on the server
                caught = null;
            }
        }
    }

    if (caught != null) {
        responsePayload = GENERIC_FAILURE_MSG;
        // servletContext may be null (for example, when unit testing)
        /**
         * Our logger will not be servlet context's log (we don't have
         * direct access to it at this point)
         * @author rlogman@gmail.com
         */
        if (logger != null) {
            // Log the exception server side
            logger.error("Exception while dispatching incoming RPC call", caught);
        }
    }

    // Let subclasses see the serialized response.
    //
    onAfterResponseSerialized(responsePayload);

    return responsePayload;
}

From source file:org.apereo.portal.portlets.portletadmin.PortletAdministrationHelper.java

/**
 * Construct a new PortletDefinitionForm for the given IPortletDefinition id.
 * If a PortletDefinition matching this ID already exists, the form will
 * be pre-populated with the PortletDefinition's current configuration.  If
 * the PortletDefinition does not yet exist, a new default form will be
 * created.//from w w w  . j  a v  a 2s  .c o  m
 *
 * @param person        user that is required to have related lifecycle permission
 * @param portletId     identifier for the portlet definition
 * @return              {@PortletDefinitionForm} with set values based on portlet definition
 *                      or default category and principal if no definition is found
 */
public PortletDefinitionForm createPortletDefinitionForm(IPerson person, String portletId) {

    IPortletDefinition def = portletDefinitionRegistry.getPortletDefinition(portletId);

    // create the new form
    final PortletDefinitionForm form;
    if (def != null) {
        // if this is a pre-existing portlet, set the category and permissions
        form = new PortletDefinitionForm(def);
        form.setId(def.getPortletDefinitionId().getStringId());

        // create a JsonEntityBean for each current category and add it
        // to our form bean's category list
        Set<PortletCategory> categories = portletCategoryRegistry.getParentCategories(def);
        for (PortletCategory cat : categories) {
            form.addCategory(new JsonEntityBean(cat));
        }

        addSubscribePermissionsToForm(def, form);
    } else {
        form = createNewPortletDefinitionForm();
    }

    /* TODO:  Service-Layer Security Reboot (great need of refactoring with a community-approved plan in place) */
    // User must have SOME FORM of lifecycle permission over AT LEAST ONE
    // category in which this portlet resides;  lifecycle permissions are
    // hierarchical, so we'll test with the weakest.
    if (!hasLifecyclePermission(person, PortletLifecycleState.CREATED, form.getCategories())) {
        logger.warn("User '" + person.getUserName()
                + "' attempted to edit the following portlet without MANAGE permission:  " + def);
        throw new SecurityException("Not Authorized");
    }

    return form;
}

From source file:com.buession.mcrypt.Mcrypt.java

/**
 * //  www.  j a v  a 2s.c om
 * 
 * @param object
 *        ?
 * @return ?
 */
public String encode(final Object object) {
    if (object == null) {
        throw new IllegalArgumentException("String could not be null");
    }

    if (algo == null || algo.length() == 0) {
        throw new RuntimeException("Algo could not be null");
    }

    try {
        MessageDigest messageDigest = provider == null ? MessageDigest.getInstance(algo)
                : MessageDigest.getInstance(algo, provider);

        if (object instanceof char[]) {
            return encode(new String((char[]) object), messageDigest);
        } else if (object instanceof byte[]) {
            return encode(new String((byte[]) object, characterEncoding), messageDigest);
        } else {
            return encode(object.toString(), messageDigest);
        }
    } catch (final NoSuchAlgorithmException e) {
        logger.error(e.getMessage());
        throw new SecurityException(e);
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage());
    }

    return null;
}

From source file:es.caib.seycon.ng.servei.PuntEntradaServiceImpl.java

/**
 * @see es.caib.seycon.ng.servei.PuntEntradaService#update(es.caib.seycon.ng.comu.PuntEntrada)
 */// www.  j ava  2 s.c  o  m
protected es.caib.seycon.ng.comu.PuntEntrada handleUpdate(es.caib.seycon.ng.comu.PuntEntrada puntEntrada)
        throws java.lang.Exception {

    if (!canAdmin(puntEntrada))
        throw new SecurityException(Messages.getString("PuntEntradaServiceImpl.UnauthorizedToUpdate")); //$NON-NLS-1$

    // Validem el XML si no s buit
    if (puntEntrada.getXmlPUE() != null && !"".equals(puntEntrada.getXmlPUE())) { //$NON-NLS-1$
        String resValida = validaXMLPUE(puntEntrada);
        if (resValida != null && !"".equals(resValida.trim())) //$NON-NLS-1$
            throw new SeyconException(
                    String.format(Messages.getString("PuntEntradaServiceImpl.XMLValidationError"), //$NON-NLS-1$
                            puntEntrada.getNom(), resValida));
    }

    // Transformem a Entity
    PuntEntradaEntity entity = getPuntEntradaEntityDao().load(puntEntrada.getId());
    boolean updatingRoot = entity != null && ROOT_TAG.equals(entity.getCodi());
    getPuntEntradaEntityDao().puntEntradaToEntity(puntEntrada, entity, true);
    if (updatingRoot) {
        entity.setCodi(ROOT_TAG);
    } else {
        if (ROOT_TAG.equals(puntEntrada.getCodi())) {
            entity.setCodi(null);
        }
    }

    // Si s e tipus men, esborrem execucions:
    if ("S".equals(puntEntrada.getMenu())) { //$NON-NLS-1$
        entity.setMetodesExecucio(new HashSet<ExecucioPuntEntradaEntity>()); // esborrem
                                                                             // execucions
    }

    // Verifiquem les icones:
    // ACTUALITZACIONS
    // UPDATE: Ja t icona, i s'ha posta una nova
    if (entity.getIcona1() != null && puntEntrada.getImgIcona1() != null
            && puntEntrada.getImgIcona1().length != 0 && puntEntrada.getIdIcona1() == null) {
        // Esborrem l'icona anterior
        getIconaEntityDao().remove(entity.getIcona1()); // Per id
        // S'ha actualitzat l'icona: creem una nova
        IconaEntity icona1 = createIcona(puntEntrada.getImgIcona1());
        entity.setIcona1(icona1.getId());
    }
    if (entity.getIcona2() != null && puntEntrada.getImgIcona2() != null
            && puntEntrada.getImgIcona2().length != 0 && puntEntrada.getIdIcona2() == null) {
        // Esborrem l'icona anterior
        getIconaEntityDao().remove(entity.getIcona2()); // Per id
        // S'ha actualitzat l'icona: creem una nova
        IconaEntity icona2 = createIcona(puntEntrada.getImgIcona2());
        entity.setIcona2(icona2.getId());
    }
    // ADD: NOVES ICONES (no existien abans)
    if (entity.getIcona1() == null && puntEntrada.getImgIcona1() != null
            && puntEntrada.getImgIcona1().length != 0) {
        // Creem l'icona
        IconaEntity icona1 = createIcona(puntEntrada.getImgIcona1());
        entity.setIcona1(icona1.getId());
    }
    if (entity.getIcona2() == null && puntEntrada.getImgIcona2() != null
            && puntEntrada.getImgIcona2().length != 0) {
        // S'ha actualitzat l'icona: creem una nova
        IconaEntity icona2 = createIcona(puntEntrada.getImgIcona2());
        entity.setIcona2(icona2.getId());
    }
    // DELETE: Esborrem l'icona assignada
    if (entity.getIcona1() != null && puntEntrada.getImgIcona1() == null) {
        // Esborrem l'icona anterior
        getIconaEntityDao().remove(entity.getIcona1()); // Per id
        entity.setIcona1(null);
    }
    if (entity.getIcona2() != null && puntEntrada.getImgIcona2() == null) {
        // Esborrem l'icona anterior
        getIconaEntityDao().remove(entity.getIcona2()); // Per id
        entity.setIcona2(null);
    }

    getPuntEntradaEntityDao().update(entity);

    auditarPuntEntrada("U", entity.getNom()); //$NON-NLS-1$

    return getPuntEntradaEntityDao().toPuntEntrada(entity);
}

From source file:org.directwebremoting.dwrp.PollHandler.java

/**
 * Check that this request is not subject to a CSRF attack
 * @param request The original browser's request
 * @param bodySessionId The session id /*from   w  w  w. j  a  va  2 s.  c om*/
 */
private void checkNotCsrfAttack(HttpServletRequest request, String bodySessionId) {
    // A check to see that this isn't a csrf attack
    // http://en.wikipedia.org/wiki/Cross-site_request_forgery
    // http://www.tux.org/~peterw/csrf.txt
    if (request.isRequestedSessionIdValid() && request.isRequestedSessionIdFromCookie()) {
        String headerSessionId = request.getRequestedSessionId();
        if (headerSessionId.length() > 0) {
            // Normal case; if same session cookie is supplied by DWR and
            // in HTTP header then all is ok
            if (headerSessionId.equals(bodySessionId)) {
                return;
            }

            // Weblogic adds creation time to the end of the incoming
            // session cookie string (even for request.getRequestedSessionId()).
            // Use the raw cookie instead
            Cookie[] cookies = request.getCookies();
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals(sessionCookieName) && cookie.getValue().equals(bodySessionId)) {
                    return;
                }
            }

            // Otherwise error
            log.error("A request has been denied as a potential CSRF attack.");
            throw new SecurityException("Session Error");
        }
    }
}

From source file:org.jnode.driver.Device.java

/**
 * @param manager The manager to set./*w  w  w  .  j a  v  a 2s .c o m*/
 */
final void setManager(AbstractDeviceManager manager) {
    if (this.manager != null) {
        throw new SecurityException("Cannot overwrite the device manager");
    } else {
        this.manager = manager;
    }
}