List of usage examples for java.lang SecurityException SecurityException
public SecurityException(Throwable cause)
From source file:FireWallClassLoader.java
/** * Constructor./*from w w w.jav a 2 s .c om*/ * * @param parent The Parent ClassLoader to use. * @param fs A set of filters to let through. The filters and be either in * package form (<CODE>org.omg.</CODE> or <CODE>org.omg.*</CODE>) * or specify a single class (<CODE>junit.framework.TestCase</CODE>). * <P> * When the package form is used, all classed in all subpackages * of this package are let trough the firewall. When the class * form is used, the filter only lets that single class through. * Note that when that class depends on another class, this class * does not need to be mentioned as a filter, because if the * originating class is loaded by the parent classloader, the * FireWallClassLoader will not receive requests for the * dependant class. * @param negativeFs List of negative filters to use. Negative filters take * precedence over positive filters. When a class or resource is * requested that matches a negative filter it is not let through * the firewall even if an allowing filter would exist in the * positive filter list. */ public FireWallClassLoader(ClassLoader parent, String[] fs, String[] negativeFs) { super(parent); this.filters = processFilters(fs); this.negativeFilters = processFilters(negativeFs); this.fnFilters = filters2FNFilters(this.filters); this.negativeFNFilters = filters2FNFilters(this.negativeFilters); boolean javaCovered = false; if (this.filters == null) { javaCovered = true; } else { for (int i = 0; i < this.filters.length; i++) { if (this.filters[i].equals("java.")) { javaCovered = true; } } } if (this.negativeFilters != null) { String java = "java."; // try all that would match java: j, ja, jav, java and java. for (int i = java.length(); i >= 0; i--) { for (int j = 0; j < this.negativeFilters.length; j++) { if (negativeFilters[j].equals(java.substring(0, i))) { javaCovered = false; } } } } if (!javaCovered) { throw new SecurityException("It's unsafe to construct a " + "FireWallClassLoader that does not let the java. " + "package through."); } }
From source file:v7cr.V7CR.java
@Override public Window getWindow(String name) { Window x = super.getWindow(name); if (x != null) return x; if (name.contains("-")) { String[] pjt_rev = StringUtils.split(name, '-'); // project name could contain spaces if (pjt_rev.length > 2) { pjt_rev = new String[] { StringUtils.join(pjt_rev, '-', 0, pjt_rev.length - 1), pjt_rev[pjt_rev.length - 1] }; }/*from ww w . j a v a 2 s . c om*/ // check permission to access the project if (!getRoles().containsKey("project:" + pjt_rev[0])) { throw new SecurityException("permission denied to access project " + pjt_rev[0]); } Object reviewId = findId("reviews", new BasicDBObject("p", pjt_rev[0]).append("svn.rev", Long.parseLong(pjt_rev[1]))); if (reviewId instanceof ObjectId) { Window reviewWindow = new Window(name); reviewWindow.addComponent(new ReviewTab((ObjectId) reviewId)); addWindow(reviewWindow); return reviewWindow; } throw new IllegalArgumentException(name); } return null; }
From source file:de.itsvs.cwtrpc.core.DefaultExtendedSerializationPolicyProvider.java
protected String getRelativeModuleBasePath(HttpServletRequest request, String moduleBasePath) throws IncompatibleRemoteServiceException, SecurityException { final String contextPath; final String relativeModuleBasePath; contextPath = request.getContextPath(); if (!moduleBasePath.startsWith(contextPath)) { throw new IncompatibleRemoteServiceException( "Module base URL is invalid " + "(does not start with context path)"); }//from ww w.j a v a2s . com relativeModuleBasePath = moduleBasePath.substring(contextPath.length()); if (!relativeModuleBasePath.startsWith("/") || !relativeModuleBasePath.endsWith("/")) { throw new IncompatibleRemoteServiceException( "Module base URL is invalid (must start and end with slash)"); } if (relativeModuleBasePath.contains("/..")) { throw new SecurityException( "Specified module base URL contains " + "relative path to sub directory: " + moduleBasePath); } return relativeModuleBasePath; }
From source file:cn.newgxu.lab.info.service.impl.NoticeServiceImpl.java
/** * 1???2????/*from w w w. ja v a2 s . c o m*/ * @param notice * @param i * @throws SecurityException */ private void assertBelong(Notice notice, Notice i) throws SecurityException { Assert.notNull("????", i); if (!i.getUser().equals(notice.getUser())) { throw new SecurityException( "????????"); } }
From source file:be.fedict.eid.idp.sp.protocol.ws_federation.sts.SecurityTokenServiceClient.java
/** * Validates the given SAML assertion via the eID IdP WS-Trust STS * validation service./*from www . ja va 2 s . com*/ * * @param samlAssertionElement * the SAML assertion DOM element to be validated. * @param expectedSAMLAudience * the optional (but recommended) expected value for SAML * Audience. */ public void validateToken(Element samlAssertionElement, String expectedSAMLAudience) { RequestSecurityTokenType request = this.objectFactory.createRequestSecurityTokenType(); List<Object> requestContent = request.getAny(); requestContent.add(this.objectFactory.createRequestType(WSTrustConstants.VALIDATE_REQUEST_TYPE)); requestContent.add(this.objectFactory.createTokenType(WSTrustConstants.STATUS_TOKEN_TYPE)); ValidateTargetType validateTarget = this.objectFactory.createValidateTargetType(); requestContent.add(this.objectFactory.createValidateTarget(validateTarget)); BindingProvider bindingProvider = (BindingProvider) this.port; WSSecuritySoapHandler.setAssertion(samlAssertionElement, bindingProvider); SecurityTokenReferenceType securityTokenReference = this.wsseObjectFactory .createSecurityTokenReferenceType(); validateTarget.setAny(this.wsseObjectFactory.createSecurityTokenReference(securityTokenReference)); securityTokenReference.getOtherAttributes().put( new QName(WSTrustConstants.WS_SECURITY_11_NAMESPACE, "TokenType"), WSTrustConstants.SAML2_WSSE11_TOKEN_TYPE); KeyIdentifierType keyIdentifier = this.wsseObjectFactory.createKeyIdentifierType(); securityTokenReference.getAny().add(this.wsseObjectFactory.createKeyIdentifier(keyIdentifier)); String samlAssertionId = samlAssertionElement.getAttribute("ID"); LOG.debug("SAML assertion ID: " + samlAssertionId); keyIdentifier.setValue(samlAssertionId); keyIdentifier.getOtherAttributes().put(new QName(WSTrustConstants.WS_SECURITY_NAMESPACE, "ValueType"), "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID"); if (null != expectedSAMLAudience) { AppliesTo appliesTo = this.policyObjectFactory.createAppliesTo(); requestContent.add(appliesTo); EndpointReferenceType endpointReference = this.addrObjectFactory.createEndpointReferenceType(); appliesTo.getAny().add(this.addrObjectFactory.createEndpointReference(endpointReference)); AttributedURIType address = this.addrObjectFactory.createAttributedURIType(); endpointReference.setAddress(address); address.setValue(expectedSAMLAudience); } RequestSecurityTokenResponseCollectionType response = this.port.requestSecurityToken(request); if (null == response) { throw new SecurityException("missing RSTRC"); } List<RequestSecurityTokenResponseType> responseList = response.getRequestSecurityTokenResponse(); if (1 != responseList.size()) { throw new SecurityException("response list should contain 1 entry"); } RequestSecurityTokenResponseType requestSecurityTokenResponse = responseList.get(0); List<Object> requestSecurityTokenResponseContent = requestSecurityTokenResponse.getAny(); boolean hasStatus = false; for (Object requestSecurityTokenResponseObject : requestSecurityTokenResponseContent) { if (requestSecurityTokenResponseObject instanceof JAXBElement) { JAXBElement jaxbElement = (JAXBElement) requestSecurityTokenResponseObject; QName qname = jaxbElement.getName(); if (WSTrustConstants.TOKEN_TYPE_QNAME.equals(qname)) { String tokenType = (String) jaxbElement.getValue(); if (false == WSTrustConstants.STATUS_TOKEN_TYPE.equals(tokenType)) { throw new SecurityException("invalid response token type: " + tokenType); } } else if (STATUS_QNAME.equals(qname)) { StatusType status = (StatusType) jaxbElement.getValue(); String statusCode = status.getCode(); if (false == WSTrustConstants.VALID_STATUS_CODE.equals(statusCode)) { String reason = status.getReason(); throw new SecurityException("invalid token: " + reason); } hasStatus = true; } } } if (false == hasStatus) { throw new SecurityException("missing wst:Status"); } }
From source file:cn.newgxu.lab.info.controller.AuthController.java
/** * REST API????/*from w w w . jav a 2 s. c o m*/ * @param model * @param session * @param uid * @param modifying ???false * @return */ @RequestMapping(value = "/users/{uid}", method = RequestMethod.GET) public String profile(Model model, HttpSession session, @PathVariable("uid") long uid, @RequestParam(value = "modifying", required = false) boolean modifying) { AuthorizedUser au = null; // ?html if (modifying) { au = checkLogin(session); Assert.notNull("?????", au); if (au.getId() != uid) { throw new SecurityException("????"); } model.addAttribute("user", au); return Config.APP + "/user_modifying"; } // ?? au = authService.find(uid); Assert.notNull("???", au); model.addAttribute(ViewConstants.AJAX_STATUS, "ok"); model.addAttribute("user", au); return ViewConstants.BAD_REQUEST; }
From source file:org.apache.bookkeeper.tls.TLSContextFactory.java
private void createClientContext(AbstractConfiguration conf) throws SecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, InvalidKeySpecException, NoSuchProviderException { final SslContextBuilder sslContextBuilder; final ClientConfiguration clientConf; final SslProvider provider; final boolean clientAuthentication; // get key-file and trust-file locations and passwords if (!(conf instanceof ClientConfiguration)) { throw new SecurityException("Client configruation not provided"); }//from w ww . java 2 s .co m clientConf = (ClientConfiguration) conf; provider = getTLSProvider(clientConf.getTLSProvider()); clientAuthentication = clientConf.getTLSClientAuthentication(); switch (KeyStoreType.valueOf(clientConf.getTLSTrustStoreType())) { case PEM: if (Strings.isNullOrEmpty(clientConf.getTLSTrustStore())) { throw new SecurityException("CA Certificate required"); } sslContextBuilder = SslContextBuilder.forClient().trustManager(new File(clientConf.getTLSTrustStore())) .ciphers(null).sessionCacheSize(0).sessionTimeout(0).sslProvider(provider) .clientAuth(ClientAuth.REQUIRE); break; case JKS: // falling thru, same as PKCS12 case PKCS12: TrustManagerFactory tmf = initTrustManagerFactory(clientConf.getTLSTrustStoreType(), clientConf.getTLSTrustStore(), clientConf.getTLSTrustStorePasswordPath()); sslContextBuilder = SslContextBuilder.forClient().trustManager(tmf).ciphers(null).sessionCacheSize(0) .sessionTimeout(0).sslProvider(provider).clientAuth(ClientAuth.REQUIRE); break; default: throw new SecurityException("Invalid Truststore type: " + clientConf.getTLSTrustStoreType()); } if (clientAuthentication) { switch (KeyStoreType.valueOf(clientConf.getTLSKeyStoreType())) { case PEM: final String keyPassword; if (Strings.isNullOrEmpty(clientConf.getTLSCertificatePath())) { throw new SecurityException("Valid Certificate is missing"); } if (Strings.isNullOrEmpty(clientConf.getTLSKeyStore())) { throw new SecurityException("Valid Key is missing"); } if (!Strings.isNullOrEmpty(clientConf.getTLSKeyStorePasswordPath())) { keyPassword = getPasswordFromFile(clientConf.getTLSKeyStorePasswordPath()); } else { keyPassword = null; } sslContextBuilder.keyManager(new File(clientConf.getTLSCertificatePath()), new File(clientConf.getTLSKeyStore()), keyPassword); break; case JKS: // falling thru, same as PKCS12 case PKCS12: KeyManagerFactory kmf = initKeyManagerFactory(clientConf.getTLSKeyStoreType(), clientConf.getTLSKeyStore(), clientConf.getTLSKeyStorePasswordPath()); sslContextBuilder.keyManager(kmf); break; default: throw new SecurityException("Invalid Keyfile type" + clientConf.getTLSKeyStoreType()); } } sslContext = sslContextBuilder.build(); }
From source file:com.glaf.core.security.SecurityUtils.java
/** * keystore?//from w w w . ja v a 2 s .c o m * * @return key ? */ public static Key getPrivateKeyFromKeystore(InputStream ksInputStream, String password, String alias) { try { KeyStore ks = KeyStore.getInstance("JKS", "SUN"); ks.load(ksInputStream, password.toCharArray()); Key privateKey = (PrivateKey) ks.getKey(alias, password.toCharArray()); return privateKey; } catch (Exception ex) { throw new SecurityException(ex); } }
From source file:com.auditbucket.engine.service.TrackService.java
/** * When you have no API key, find if authorised * @param metaKey known GUID//w ww .ja v a2s . co m * @return header the caller is authorised to view */ public MetaHeader getHeader(@NotEmpty String metaKey) { String userName = securityHelper.getLoggedInUser(); SystemUser su = sysUserService.findByName(userName); if (su == null) throw new SecurityException(userName + "Not authorised to retrieve headers"); return getHeader(su.getCompany(), metaKey, false); }
From source file:com.mycom.products.mywebsite.backend.util.UploadHandler.java
@Override @ResponseBody/*from ww w.j a va 2 s . co m*/ @RequestMapping(method = RequestMethod.POST) protected final void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); PrintWriter writer = response.getWriter(); // checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush(); return; } JSONObject json = new JSONObject(); SimpleDateFormat fmtYMD = new SimpleDateFormat("/" + "yyyyMMdd"); Date today = new Date(); String uploadPath = EntryPoint.getUploadPath() + "/"; try { List<FileItem> items = uploadHandler.parseRequest(request); if (items != null && items.size() > 0) { String saveDir = "", fileCategory = ""; for (FileItem item : items) { if (item.isFormField()) { fileCategory = item.getString(); } } saveDir = fileCategory + fmtYMD.format(today); // creates the directory if it does not exist File uploadDir = new File(uploadPath + saveDir); if (!uploadDir.exists()) { uploadDir.mkdirs(); } List<HashMap<String, String>> uploadFiles = new ArrayList<>(); for (FileItem item : items) { // processes only fields that are not form fields if (!item.isFormField()) { if (saveDir.length() == 0) { json.put("messageCode", "V1001"); json.put("messageParams", "File upload type"); json.put("status", HttpStatus.BAD_REQUEST); response.setContentType("application/json"); writer.write(json.toString()); writer.flush(); } String originalFileName = "", saveFileName = "", format = "", fileSize = ""; // set the default format to png when it is profileImage if (fileCategory.equals("profilePicture")) { format = ".png"; } // can't predict fileName and format would be included. // For instance, blob won't be. try { originalFileName = item.getName().substring(0, item.getName().lastIndexOf(".")); } catch (Exception e) { // Nothing to do. Skip } try { format = item.getName().substring(item.getName().lastIndexOf("."), item.getName().length()); } catch (Exception e) { // Nothing to do. Skip } fileSize = getReadableFileSize(item.getSize()); UUID uuid = UUID.randomUUID(); saveFileName = new File(uuid.toString() + format).getName(); String filePath = uploadPath + saveDir + "/" + saveFileName; if (fileCategory.equals("profilePicture")) { saveProfileImage(item, filePath); } // Time to save in DB LoggedUserBean loginUser; Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof LoggedUserBean) { loginUser = (LoggedUserBean) principal; } else { throw new SecurityException("Unauthorize File Upload process was attempted."); } StaticContentBean content = new StaticContentBean(); content.setFileName(originalFileName + format); content.setFilePath(filePath); content.setFileSize(fileSize); content.setFileType(FileType.valueOf(getFileType(format))); long lastInsertedId = contentService.insert(content, loginUser.getId()); // else .... other file types go here HashMap<String, String> fileItem = new HashMap<>(); fileItem.put("contentId", "" + lastInsertedId); uploadFiles.add(fileItem); } } json.put("uploadFiles", uploadFiles); json.put("status", HttpStatus.OK); response.setContentType("application/json"); writer.write(json.toString()); writer.flush(); } } catch (FileUploadException e) { throw new RuntimeException("File upload Error !", e); } catch (Exception e) { throw new RuntimeException("File upload Error !", e); } finally { writer.close(); } }