List of usage examples for java.lang SecurityException SecurityException
public SecurityException(Throwable cause)
From source file:ch.rasc.wampspring.method.WampAnnotationMethodMessageHandler.java
private static void checkAuthentication(WampHandlerMethod handlerMethod, WampMessage message) { WampSession wampSession = message.getWampSession(); if (wampSession != null && !wampSession.isAuthenticated() && handlerMethod.isAuthenticationRequired()) { if (!(message instanceof UnsubscribeMessage && ((UnsubscribeMessage) message).isCleanup())) { throw new SecurityException("Not authenticated"); }//from w w w .j a v a2 s . c om } }
From source file:org.commonreality.reality.impl.handler.ConnectionTracker.java
/** * check to see if the connection should be accepted based on the credentials. * If it is to be accepted, the connection will be accepted provisionally and * an {@link IIdentifier} will be assigned to the participant. The connection * is not officially connected, however, until * {@link #authorizeConnection(IIdentifier, ICredentials)} is called. * //from ww w . j a v a 2 s. c o m * @param credentials * @param session * @param addressInfo * @param template * @return */ synchronized public IIdentifier acceptConnection(ICredentials credentials, IoSession session, IAddressingInformation addressInfo, IIdentifier template) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Connection request from " + session); if (_validCredentials.contains(credentials) || _promiscuous) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Credentials passed"); if (_acceptedConnections.get(credentials) == null) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Not already connected"); validateAddressing(session, addressInfo); IIdentifier identifier = _reality.newIdentifier(_reality.getIdentifier(), template); session.setAttribute(CREDENTIALS, credentials); session.setAttribute(IDENTIFIER, identifier); _pendingAddressInfo.put(identifier, addressInfo); _pendingConnections.put(credentials, session); _pendingSessionMap.put(identifier, session); if (LOGGER.isDebugEnabled()) { LOGGER.debug("We can accept the connection from " + session + " with " + credentials); LOGGER.debug("Granting " + identifier); } return identifier; } throw new SecurityException("Cannot accept connection because credentials are already in use"); } throw new SecurityException("Cannot accept connection because credentials are invalid"); }
From source file:be.fedict.eid.idp.protocol.ws_federation.sts.SecurityTokenServicePortImpl.java
private void validateToken(Element tokenElement, String expectedAudience, IdentityProviderConfiguration identityProviderConfiguration) throws Exception { List<X509Certificate> certificateChain = identityProviderConfiguration.getIdentityCertificateChain(); if (certificateChain.isEmpty()) { throw new SecurityException("no eID IdP service identity configured"); }// ww w . j a va2 s. c o m Element nsElement = tokenElement.getOwnerDocument().createElement("nsElement"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:saml2", "urn:oasis:names:tc:SAML:2.0:assertion"); LOG.debug("token element: " + tokenElement.getLocalName()); LOG.debug("token element namespace: " + tokenElement.getNamespaceURI()); LOG.debug("token: " + toString(tokenElement)); // fix for recent versions of Apache xmlsec. tokenElement.setIdAttribute("ID", true); Element signatureElement = (Element) XPathAPI.selectSingleNode(tokenElement, "ds:Signature", nsElement); if (null == signatureElement) { throw new SecurityException("missing XML signature"); } XMLSignature xmlSignature = new XMLSignature(signatureElement, ""); KeyInfo keyInfo = xmlSignature.getKeyInfo(); X509Certificate actualCertificate = keyInfo.getX509Certificate(); boolean signatureResult = xmlSignature.checkSignatureValue(actualCertificate); if (false == signatureResult) { throw new SecurityException("invalid XML signature"); } LOG.debug("XML signature OK"); X509Certificate serviceCertificate = certificateChain.get(0); if (false == Arrays.equals(serviceCertificate.getEncoded(), actualCertificate.getEncoded())) { throw new SecurityException("SAML signing certificate different from eID IdP service identity"); } LOG.debug("SAML signer OK"); String actualIssuer = XPathAPI.selectSingleNode(tokenElement, "saml2:Issuer/text()", nsElement) .getNodeValue(); String serviceIssuer = identityProviderConfiguration.getDefaultIssuer(); if (false == actualIssuer.equals(serviceIssuer)) { LOG.debug("actual issuer: " + actualIssuer); LOG.debug("service issuer: " + serviceIssuer); throw new SecurityException("wrong SAML issuer"); } LOG.debug("SAML issuer OK"); if (null != expectedAudience) { String audience = XPathAPI .selectSingleNode(tokenElement, "saml2:Conditions/saml2:AudienceRestriction/saml2:Audience/text()", nsElement) .getNodeValue(); if (false == expectedAudience.equals(audience)) { LOG.debug("expected audience: " + expectedAudience); LOG.debug("actual audience: " + audience); throw new SecurityException("incorrect SAML audience"); } LOG.debug("SAML Audience OK"); } else { LOG.warn("SAML audience restriction not checked"); } String authnContextClassRef = XPathAPI .selectSingleNode(tokenElement, "saml2:AuthnStatement/saml2:AuthnContext/saml2:AuthnContextClassRef/text()", nsElement) .getNodeValue(); LOG.debug("AuthnContextClassRef: " + authnContextClassRef); SamlAuthenticationPolicy samlAuthenticationPolicy = SamlAuthenticationPolicy .getAuthenticationPolicy(authnContextClassRef); if (SamlAuthenticationPolicy.AUTHENTICATION != samlAuthenticationPolicy && SamlAuthenticationPolicy.AUTHENTICATION_WITH_IDENTIFICATION != samlAuthenticationPolicy) { throw new SecurityException("wrong SAML authentication policy: " + samlAuthenticationPolicy); } String notBeforeStr = XPathAPI.selectSingleNode(tokenElement, "saml2:Conditions/@NotBefore", nsElement) .getNodeValue(); String notOnOrAfterStr = XPathAPI .selectSingleNode(tokenElement, "saml2:Conditions/@NotOnOrAfter", nsElement).getNodeValue(); DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeParser(); DateTime notBefore = dateTimeFormatter.parseDateTime(notBeforeStr); DateTime notOnOrAfter = dateTimeFormatter.parseDateTime(notOnOrAfterStr); DateTime now = new DateTime(); if (now.isBefore(notBefore)) { throw new SecurityException("SAML assertion in future"); } if (now.isAfter(notOnOrAfter)) { throw new SecurityException("SAML assertion expired"); } LOG.debug("SAML timestamp OK"); }
From source file:net.sourceforge.jencrypt.CommandLineHelper.java
/** * Check if the decryption destination directory, base directory and key * file exists./*from w ww. ja va 2s.c o m*/ * * @throws IOException */ public boolean isValid() throws IOException { // Cipheroptions contains -end or -dec if (cipherOptions != null && configFileString != null && passwordString != null) { File source = new File(sourceFileOrFolder); if (this.getCipherMode() == Cipher.DECRYPT_MODE) { if (targetPath == "") { targetPath = System.getProperty("user.dir"); } File target = new File(targetPath); if (!source.exists()) { throw new IOException("Source archive '" + sourceFileOrFolder + "' does not exist."); } else if (!source.isFile()) { throw new IOException("Source archive '" + sourceFileOrFolder + "' is not a file"); } if (!target.exists() || !target.canWrite()) { throw new IOException("Destination '" + target.getName() + "' not found or access denied"); } } if (this.getCipherMode() == Cipher.ENCRYPT_MODE) { File targetFile = new File(targetPath); if (targetFile.isDirectory()) { throw new IOException("Destination '" + targetFile.getName() + "' is not a file"); } else if (targetFile.exists()) { throw new IOException("File '" + targetFile.getName() + "' already exists"); } else { try { targetFile.createNewFile(); } catch (IOException e) { throw new SecurityException("Can't create file '" + targetPath + "': " + e.getMessage()); } finally { targetFile.delete(); } } if (!source.exists() || !source.canRead()) { throw new IOException( "Folder to encrypt '" + source.getName() + "' not found or access denied"); } } return true; } return false; }
From source file:org.eclipse.wb.internal.core.DesignerPlugin.java
/** * We should not allow user code to terminate JVM. *//*ww w. j a va 2 s. c o m*/ public static void installSecurityManager() { System.setSecurityManager(new SecurityManager() { @Override public void checkPermission(java.security.Permission perm) { if (isExitVM(perm)) { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); for (StackTraceElement element : stackTrace) { String className = element.getClassName(); String methodName = element.getMethodName(); // ignore this class, because it has our class name prefix if (className.equals(getClass().getName())) { continue; } // ignore JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); if (className.equals("javax.swing.JFrame") && methodName.equals("setDefaultCloseOperation")) { return; } // prevent exit() from user invoked by "designer" if (className.startsWith("org.eclipse.wb.") || className.startsWith("com.google.gdt.eclipse.designer.") || className.startsWith("net.rim.ejde.designer.") || className.startsWith("java.awt.EventQueue")) { // we often use test_exit() method as point to stop tests, allow it if (methodName.startsWith("test_") && methodName.endsWith("_exit")) { return; } // prevent exit() throw new SecurityException("Exit from within user-loaded code"); } } } } private boolean isExitVM(java.security.Permission perm) { return perm instanceof RuntimePermission && StringUtils.startsWith(perm.getName(), "exitVM"); } }); }
From source file:org.madsonic.service.MediaFileService.java
public MediaFile getMediaFile(int id) { MediaFile mediaFile = mediaFileDao.getMediaFile(id); if (mediaFile == null) { return null; }/*www .ja va 2s . co m*/ if (!mediaFile.getPath().startsWith("http")) { if (!securityService.isReadAllowed(mediaFile.getFile())) { throw new SecurityException("Access denied to file " + mediaFile); } } return checkLastModified(mediaFile, settingsService.isFastCacheEnabled()); }
From source file:org.fao.geonet.api.records.MetadataWorkflowApi.java
@ApiOperation(value = "Get last workflow status for a record", notes = "", nickname = "getStatus") @RequestMapping(value = "/{metadataUuid}/status/workflow/last", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) @PreAuthorize("hasRole('Editor')") @ApiResponses(value = { @ApiResponse(code = 200, message = "Record status."), @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_EDIT) }) @ResponseStatus(HttpStatus.OK)/*from w ww .ja v a2s. co m*/ @ResponseBody public MetadataWorkflowStatusResponse getStatus( @ApiParam(value = API_PARAM_RECORD_UUID, required = true) @PathVariable String metadataUuid, HttpServletRequest request) throws Exception { AbstractMetadata metadata = ApiUtils.canEditRecord(metadataUuid, request); ApplicationContext appContext = ApplicationContextHolder.get(); Locale locale = languageUtils.parseAcceptLanguage(request.getLocales()); ServiceContext context = ApiUtils.createServiceContext(request, locale.getISO3Language()); AccessManager am = appContext.getBean(AccessManager.class); //--- only allow the owner of the record to set its status if (!am.isOwner(context, String.valueOf(metadata.getId()))) { throw new SecurityException(String.format( "Only the owner of the metadata can get the status. User is not the owner of the metadata")); } IMetadataStatus metadataStatus = context.getBean(IMetadataStatus.class); MetadataStatus recordStatus = metadataStatus.getStatus(metadata.getId()); // List<StatusValue> elStatus = context.getBean(StatusValueRepository.class).findAll(); List<StatusValue> elStatus = context.getBean(StatusValueRepository.class) .findAllByType(StatusValueType.workflow); //--- get the list of content reviewers for this metadata record Set<Integer> ids = new HashSet<Integer>(); ids.add(Integer.valueOf(metadata.getId())); List<Pair<Integer, User>> reviewers = context.getBean(UserRepository.class) .findAllByGroupOwnerNameAndProfile(ids, Profile.Reviewer, SortUtils.createSort(User_.name)); List<User> listOfReviewers = new ArrayList<>(); for (Pair<Integer, User> reviewer : reviewers) { listOfReviewers.add(reviewer.two()); } return new MetadataWorkflowStatusResponse(recordStatus, listOfReviewers, am.hasEditPermission(context, metadata.getId() + ""), elStatus); }
From source file:net.shopxx.plugin.tlpay.TlpayPlugin.java
/** * @Title: MD5Encode// w w w . j a va 2 s . co m * @Description: TODO(MD5) * @param @param aData * @param @return * @param @throws SecurityException * @return String * @throws * @author Administrator */ public String MD5Encode(String aData) throws SecurityException { String resultString = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); resultString = bytes2HexString(md.digest(aData.getBytes("UTF-8"))); } catch (Exception e) { e.printStackTrace(); throw new SecurityException("MD5?"); } return resultString; }
From source file:be.fedict.eid.dss.protocol.simple.SimpleDSSProtocolService.java
private void verifyServiceSignature(String serviceSigned, String target, String signatureRequest, String signatureRequestId, String contentType, String language, String relayState, byte[] serviceSignatureValue, List<X509Certificate> serviceCertificateChain) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { LOG.debug("verifying service signature"); X509Certificate serviceCertificate = serviceCertificateChain.get(0); LOG.debug("service identity: " + serviceCertificate.getSubjectX500Principal()); Signature serviceSignature = Signature.getInstance("SHA1withRSA"); serviceSignature.initVerify(serviceCertificate); StringTokenizer serviceSignedStringTokenizer = new StringTokenizer(serviceSigned, ","); while (serviceSignedStringTokenizer.hasMoreTokens()) { String serviceSignedElement = serviceSignedStringTokenizer.nextToken(); LOG.debug("service signed: " + serviceSignedElement); byte[] data; if ("target".equals(serviceSignedElement)) { data = target.getBytes();// ww w .ja v a 2s .c o m } else if ("SignatureRequest".equals(serviceSignedElement)) { data = signatureRequest.getBytes(); } else if ("SignatureRequestId".equals(serviceSignedElement)) { data = signatureRequestId.getBytes(); } else if ("ContentType".equals(serviceSignedElement)) { data = contentType.getBytes(); } else if ("language".equals(serviceSignedElement)) { data = language.getBytes(); } else if ("RelayState".equals(serviceSignedElement)) { data = relayState.getBytes(); } else { throw new SecurityException("service signed unknown element: " + serviceSignedElement); } serviceSignature.update(data); } boolean valid = serviceSignature.verify(serviceSignatureValue); if (!valid) { throw new SecurityException("service signature not valid"); } }
From source file:de.thorstenberger.taskmodel.view.SavePageAction.java
private void processInteractiveTasklets(final ComplexTasklet ct, final List<SubTasklet> subtasklets, final List<SubmitData> submitDatas, final HttpServletRequest request) { for (int i = 0; i < subtasklets.size(); i++) { final SubTasklet subTasklet = subtasklets.get(i); if (request.getParameterMap().containsKey("doAutoCorrection_" + subTasklet.getVirtualSubtaskNumber())) { // FIXME: add TaskModelSecurityException being subclassed from // SecurityException if (!subTasklet.isInteractiveFeedback()) { throw new SecurityException( "No interactive feedback allowed for SubTaskDef " + subTasklet.getSubTaskDefId()); }/*from w w w. j a v a 2s . c om*/ ct.doInteractiveFeedback(subTasklet, submitDatas.get(i)); } } }