List of usage examples for java.lang SecurityException SecurityException
public SecurityException(Throwable cause)
From source file:edu.internet2.middleware.shibboleth.common.config.BaseService.java
/** {@inheritDoc} */ public void initialize() throws ServiceException { if (isDestroyed()) { throw new SecurityException(getId() + " service has been destroyed, it may not be initialized."); }/*from w w w .jav a2 s . c o m*/ if (isInitialized()) { return; } loadContext(); }
From source file:be.fedict.eid.idp.protocol.ws_federation.sts.SecurityTokenServicePortImpl.java
@Override public RequestSecurityTokenResponseCollectionType requestSecurityToken(RequestSecurityTokenType request) { List<Object> requestContent = request.getAny(); String expectedAudience = null; for (Object requestObject : requestContent) { LOG.debug("request object type: " + requestObject.getClass().getName()); if (requestObject instanceof JAXBElement) { JAXBElement jaxbElement = (JAXBElement) requestObject; 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); }//from w w w . j a v a 2 s . co m } else if (WSTrustConstants.REQUEST_TYPE_QNAME.equals(qname)) { String requestType = (String) jaxbElement.getValue(); if (false == WSTrustConstants.VALIDATE_REQUEST_TYPE.equals(requestType)) { throw new SecurityException("invalid request type: " + requestType); } } else if (WSTrustConstants.VALIDATE_TARGET_QNAME.equals(qname)) { ValidateTargetType validateTarget = (ValidateTargetType) jaxbElement.getValue(); Object validateTargetObject = validateTarget.getAny(); if (null == validateTargetObject) { throw new SecurityException("missing ValidateTarget content"); } LOG.debug("ValidateTarget content type: " + validateTargetObject.getClass().getName()); // TODO: verify content is indeed SecurityTokenReference } } else if (requestObject instanceof AppliesTo) { AppliesTo appliesTo = (AppliesTo) requestObject; LOG.debug("wsp:AppliesTo present"); List<Object> appliesToContent = appliesTo.getAny(); for (Object appliesToObject : appliesToContent) { LOG.debug("AppliesTo object type: " + appliesToObject.getClass().getName()); if (appliesToObject instanceof JAXBElement) { JAXBElement appliesToElement = (JAXBElement) appliesToObject; QName appliesToQName = appliesToElement.getName(); if (WSTrustConstants.ENDPOINT_REFERENCE_QNAME.equals(appliesToQName)) { EndpointReferenceType endpointReference = (EndpointReferenceType) appliesToElement .getValue(); expectedAudience = endpointReference.getAddress().getValue(); } } } } } Element tokenElement = WSSecuritySoapHandler.getToken(this.context); if (null == tokenElement) { throw new SecurityException("missing Token"); } LOG.debug("token element: " + tokenElement.getLocalName()); LOG.debug("expected audience: " + expectedAudience); ServletContext servletContext = (ServletContext) context.getMessageContext() .get(MessageContext.SERVLET_CONTEXT); IdentityProviderConfiguration identityProviderConfiguration = IdentityProviderConfigurationFactory .getInstance(servletContext); boolean valid; String reason = null; try { validateToken(tokenElement, expectedAudience, identityProviderConfiguration); valid = true; } catch (Exception e) { LOG.error("error validating SAML token: " + e.getMessage(), e); valid = false; reason = e.getMessage(); } RequestSecurityTokenResponseCollectionType responseCollection = this.objectFactory .createRequestSecurityTokenResponseCollectionType(); List<RequestSecurityTokenResponseType> requestSecurityTokenResponses = responseCollection .getRequestSecurityTokenResponse(); RequestSecurityTokenResponseType requestSecurityTokenResponse = this.objectFactory .createRequestSecurityTokenResponseType(); requestSecurityTokenResponses.add(requestSecurityTokenResponse); List<Object> rstsContent = requestSecurityTokenResponse.getAny(); rstsContent.add(this.objectFactory.createTokenType(WSTrustConstants.STATUS_TOKEN_TYPE)); StatusType status = this.objectFactory.createStatusType(); rstsContent.add(this.objectFactory.createStatus(status)); if (valid) { status.setCode(WSTrustConstants.VALID_STATUS_CODE); } else { status.setCode(WSTrustConstants.INVALID_STATUS_CODE); status.setReason(reason); } return responseCollection; }
From source file:com.cws.esolutions.security.main.PasswordUtility.java
public static void main(final String[] args) { final String methodName = PasswordUtility.CNAME + "#main(final String[] args)"; if (DEBUG) {/*from w w w . ja v a 2s.c o m*/ DEBUGGER.debug("Value: {}", methodName); } if (args.length == 0) { HelpFormatter usage = new HelpFormatter(); usage.printHelp(PasswordUtility.CNAME, options, true); System.exit(1); } BufferedReader bReader = null; BufferedWriter bWriter = null; try { // load service config first !! SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG, false); if (DEBUG) { DEBUGGER.debug("Options options: {}", options); for (String arg : args) { DEBUGGER.debug("Value: {}", arg); } } CommandLineParser parser = new PosixParser(); CommandLine commandLine = parser.parse(options, args); if (DEBUG) { DEBUGGER.debug("CommandLineParser parser: {}", parser); DEBUGGER.debug("CommandLine commandLine: {}", commandLine); DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions()); DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList()); } final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData(); final SecurityConfig secConfig = secConfigData.getSecurityConfig(); final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo(); final SystemConfig systemConfig = secConfigData.getSystemConfig(); if (DEBUG) { DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData); DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig); DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig); DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig); } if (commandLine.hasOption("encrypt")) { if ((StringUtils.isBlank(repoConfig.getPasswordFile())) || (StringUtils.isBlank(repoConfig.getSaltFile()))) { System.err.println("The password/salt files are not configured. Entries will not be stored!"); } File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile()); File saltFile = FileUtils.getFile(repoConfig.getSaltFile()); if (DEBUG) { DEBUGGER.debug("File passwordFile: {}", passwordFile); DEBUGGER.debug("File saltFile: {}", saltFile); } final String entryName = commandLine.getOptionValue("entry"); final String username = commandLine.getOptionValue("username"); final String password = commandLine.getOptionValue("password"); final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength()); if (DEBUG) { DEBUGGER.debug("String entryName: {}", entryName); DEBUGGER.debug("String username: {}", username); DEBUGGER.debug("String password: {}", password); DEBUGGER.debug("String salt: {}", salt); } final String encodedSalt = PasswordUtils.base64Encode(salt); final String encodedUserName = PasswordUtils.base64Encode(username); final String encryptedPassword = PasswordUtils.encryptText(password, salt, secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding()); final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword); if (DEBUG) { DEBUGGER.debug("String encodedSalt: {}", encodedSalt); DEBUGGER.debug("String encodedUserName: {}", encodedUserName); DEBUGGER.debug("String encodedPassword: {}", encodedPassword); } if (commandLine.hasOption("store")) { try { new File(passwordFile.getParent()).mkdirs(); new File(saltFile.getParent()).mkdirs(); boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile(); if (DEBUG) { DEBUGGER.debug("saltFileExists: {}", saltFileExists); } // write the salt out first if (!(saltFileExists)) { throw new IOException("Unable to create salt file"); } boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile(); if (!(passwordFileExists)) { throw new IOException("Unable to create password file"); } if (commandLine.hasOption("replace")) { File[] files = new File[] { saltFile, passwordFile }; if (DEBUG) { DEBUGGER.debug("File[] files: {}", (Object) files); } for (File file : files) { if (DEBUG) { DEBUGGER.debug("File: {}", file); } String currentLine = null; File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile"); if (DEBUG) { DEBUGGER.debug("File tmpFile: {}", tmpFile); } bReader = new BufferedReader(new FileReader(file)); bWriter = new BufferedWriter(new FileWriter(tmpFile)); while ((currentLine = bReader.readLine()) != null) { if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) { bWriter.write(currentLine + System.getProperty("line.separator")); bWriter.flush(); } } bWriter.close(); FileUtils.deleteQuietly(file); FileUtils.copyFile(tmpFile, file); FileUtils.deleteQuietly(tmpFile); } } FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt + System.getProperty("line.separator"), true); FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + "," + encodedPassword + System.getProperty("line.separator"), true); } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); } } System.out.println("Entry Name " + entryName + " stored."); } if (commandLine.hasOption("decrypt")) { String saltEntryName = null; String saltEntryValue = null; String decryptedPassword = null; String passwordEntryName = null; if ((StringUtils.isEmpty(commandLine.getOptionValue("entry")) && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) { throw new ParseException("No entry or username was provided to decrypt."); } if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) { throw new ParseException("no entry provided to decrypt"); } String entryName = commandLine.getOptionValue("entry"); String username = commandLine.getOptionValue("username"); if (DEBUG) { DEBUGGER.debug("String entryName: {}", entryName); DEBUGGER.debug("String username: {}", username); } File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile()); File saltFile = FileUtils.getFile(repoConfig.getSaltFile()); if (DEBUG) { DEBUGGER.debug("File passwordFile: {}", passwordFile); DEBUGGER.debug("File saltFile: {}", saltFile); } if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) { throw new IOException( "Unable to read configured password/salt file. Please check configuration and/or permissions."); } for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) { saltEntryName = lineEntry.split(",")[0]; if (DEBUG) { DEBUGGER.debug("String saltEntryName: {}", saltEntryName); } if (StringUtils.equals(saltEntryName, entryName)) { saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]); break; } } if (StringUtils.isEmpty(saltEntryValue)) { throw new SecurityException("No entries were found that matched the provided information"); } for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) { passwordEntryName = lineEntry.split(",")[0]; if (DEBUG) { DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName); } if (StringUtils.equals(passwordEntryName, saltEntryName)) { String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]); decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue, secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding()); break; } } if (StringUtils.isEmpty(decryptedPassword)) { throw new SecurityException("No entries were found that matched the provided information"); } System.out.println(decryptedPassword); } else if (commandLine.hasOption("encode")) { System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0))); } else if (commandLine.hasOption("decode")) { System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0))); } } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); System.err.println("An error occurred during processing: " + iox.getMessage()); System.exit(1); } catch (ParseException px) { ERROR_RECORDER.error(px.getMessage(), px); System.err.println("An error occurred during processing: " + px.getMessage()); System.exit(1); } catch (SecurityException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); System.err.println("An error occurred during processing: " + sx.getMessage()); System.exit(1); } catch (SecurityServiceException ssx) { ERROR_RECORDER.error(ssx.getMessage(), ssx); System.exit(1); } finally { try { if (bReader != null) { bReader.close(); } if (bWriter != null) { bReader.close(); } } catch (IOException iox) { } } System.exit(0); }
From source file:com.turn.ttorrent.client.TorrentHandler.java
@Nonnull private static TorrentByteStorage toStorage(@Nonnull Torrent torrent, @CheckForNull File parent) throws IOException { if (parent == null) throw new NullPointerException("No parent directory given."); String parentPath = parent.getCanonicalPath(); if (!torrent.isMultifile() && parent.isFile()) return new FileStorage(parent, torrent.getSize()); List<FileStorage> files = new LinkedList<FileStorage>(); long offset = 0L; for (Torrent.TorrentFile file : torrent.getFiles()) { // TODO: Files.simplifyPath() is a security check here to avoid jail-escape. // However, it uses "/" not File.separator internally. String path = Files.simplifyPath("/" + file.path); File actual = new File(parent, path); String actualPath = actual.getCanonicalPath(); if (!actualPath.startsWith(parentPath)) throw new SecurityException("Torrent file path attempted to break directory jail: " + actualPath + " is not within " + parentPath); FileUtils.forceMkdir(actual.getParentFile()); files.add(new FileStorage(actual, offset, file.size)); offset += file.size;// ww w .ja v a 2 s .c om } return new FileCollectionStorage(files, torrent.getSize()); }
From source file:com.mastercard.test.spring.security.SpringSecurityJUnit4ClassRunnerMethodAnnotationTests.java
@Test(expected = SecurityException.class) @WithSystemAdmin/* ww w . j av a 2s .co m*/ public void runningWithOneNamedUserSupportsExpectedExceptionsAndExecutesOneTime() { throw new SecurityException("Test"); }
From source file:org.fao.geonet.services.group.Update.java
public Element serviceSpecificExec(final Element params, final ServiceContext context) throws Exception { final String id = params.getChildText(Params.ID); final String name = Util.getParam(params, Params.NAME); final String description = Util.getParam(params, Params.DESCRIPTION, ""); final boolean deleteLogo = Util.getParam(params, "deleteLogo", false); final String copyLogo = Util.getParam(params, "copyLogo", null); final String email = params.getChildText(Params.EMAIL); final String category = Util.getParam(params, Params.CATEGORY, "-1"); final java.util.List<Integer> allowedCategories = Util.getParamsAsInt(params, "allowedCategories"); final Boolean enableAllowedCategories = Util.getParam(params, "enableAllowedCategories", false); String website = params.getChildText("website"); if (website != null && website.length() > 0 && !website.startsWith("http://")) { website = "http://" + website; }/*from w w w . ja v a 2s . c o m*/ //Check that we have privileges over this group UserSession session = context.getUserSession(); if (!session.getProfile().equals(Profile.Administrator)) { java.util.List<UserGroup> usergroups = context.getBean(UserGroupRepository.class) .findAll(GroupSpecs.isEditorOrMore(session.getUserIdAsInt())); boolean canEditGroup = false; if (id != null && !"".equals(id)) { Integer i = Integer.valueOf(id); for (UserGroup ug : usergroups) { if (ug.getGroup().getId() == i) { canEditGroup = ug.getProfile().equals(Profile.UserAdmin); } } } if (!canEditGroup) { throw new SecurityException("You cannot edit this group"); } } // Logo management ported/adapted from GeoNovum GeoNetwork app. // Original devs: Heikki Doeleman and Thijs Brentjens String logoFile = params.getChildText("logofile"); FilePathChecker.verify(logoFile); FilePathChecker.verify(copyLogo); final String logoUUID = copyLogo == null ? copyLogoFromRequest(context, logoFile) : copyLogoFromHarvesters(context, copyLogo); final GroupRepository groupRepository = context.getBean(GroupRepository.class); final MetadataCategoryRepository catRepository = context.getBean(MetadataCategoryRepository.class); MetadataCategory tmpcat = null; try { tmpcat = catRepository.findOne(Integer.valueOf(category)); } catch (Throwable t) { //Not a valid category id } final MetadataCategory cat = tmpcat; final Element elRes = new Element(Jeeves.Elem.RESPONSE); if (id == null || "".equals(id)) { Group group = new Group().setName(name).setDescription(description).setEmail(email).setLogo(logoUUID) .setWebsite(website).setDefaultCategory(cat) .setEnableAllowedCategories(enableAllowedCategories); setUpAllowedCategories(allowedCategories, enableAllowedCategories, catRepository, group); final LanguageRepository langRepository = context.getBean(LanguageRepository.class); java.util.List<Language> allLanguages = langRepository.findAll(); for (Language l : allLanguages) { group.getLabelTranslations().put(l.getId(), name); } groupRepository.save(group); elRes.addContent(new Element(Jeeves.Elem.OPERATION).setText(Jeeves.Text.ADDED)); } else { final String finalWebsite = website; groupRepository.update(Integer.valueOf(id), new Updater<Group>() { @Override public void apply(final Group entity) { entity.setEmail(email).setName(name).setDescription(description).setWebsite(finalWebsite) .setDefaultCategory(cat).setEnableAllowedCategories(enableAllowedCategories); setUpAllowedCategories(allowedCategories, enableAllowedCategories, catRepository, entity); if (!deleteLogo && logoUUID != null) { entity.setLogo(logoUUID); } if (deleteLogo) { entity.setLogo(null); } } }); elRes.addContent(new Element(Jeeves.Elem.OPERATION).setText(Jeeves.Text.UPDATED)); } return elRes; }
From source file:com.glaf.core.security.SecurityUtils.java
/** * ?????,??/*from www . ja v a 2 s . c o m*/ * * @param ctx * * @param symmetryKey * * @param pubKey * * @return String(?base64?) */ public static String generateDigitalEnvelope(SecurityContext ctx, Key symmetryKey, byte[] pubKey) { String result = null; InputStream inputStream = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); inputStream = new ByteArrayInputStream(pubKey); java.security.cert.Certificate cert = cf.generateCertificate(inputStream); inputStream.close(); PublicKey publicKey = cert.getPublicKey(); Cipher cipher = Cipher.getInstance(ctx.getAsymmetryAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicKey); result = Base64.encodeBase64String(cipher.doFinal(symmetryKey.getEncoded())); return result; } catch (Exception ex) { throw new SecurityException(ex); } finally { try { if (inputStream != null) { inputStream.close(); inputStream = null; } } catch (IOException ex) { } } }
From source file:org.fao.geonet.api.records.attachments.FilesystemStore.java
@Override public List<MetadataResource> getResources(ServiceContext context, String metadataUuid, MetadataResourceVisibility visibility, String filter) throws Exception { ApplicationContext _appContext = ApplicationContextHolder.get(); String metadataId = getAndCheckMetadataId(metadataUuid); GeonetworkDataDirectory dataDirectory = _appContext.getBean(GeonetworkDataDirectory.class); SettingManager settingManager = _appContext.getBean(SettingManager.class); AccessManager accessManager = _appContext.getBean(AccessManager.class); boolean canEdit = accessManager.canEdit(context, metadataId); if (visibility == MetadataResourceVisibility.PRIVATE && !canEdit) { throw new SecurityException(String.format( "User does not have privileges to get the list of '%s' resources for metadata '%s'.", visibility, metadataUuid)); }/* ww w .ja v a2 s .c o m*/ Path metadataDir = Lib.resource.getMetadataDir(dataDirectory, metadataId); Path resourceTypeDir = metadataDir.resolve(visibility.toString()); List<MetadataResource> resourceList = new ArrayList<>(); if (filter == null) { filter = FilesystemStore.DEFAULT_FILTER; } try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(resourceTypeDir, filter)) { for (Path path : directoryStream) { MetadataResource resource = new FilesystemStoreResource( UrlEscapers.urlFragmentEscaper().escape(metadataUuid) + "/attachments/" + UrlEscapers.urlFragmentEscaper().escape(path.getFileName().toString()), settingManager.getNodeURL() + "api/records/", visibility, Files.size(path)); resourceList.add(resource); } } catch (IOException ignored) { } Collections.sort(resourceList, MetadataResourceVisibility.sortByFileName); return resourceList; }
From source file:fr.letroll.ttorrentandroid.client.TorrentHandler.java
@Nonnull private static TorrentByteStorage toStorage(@Nonnull Torrent torrent, @Nonnull File parent) throws IOException { Preconditions.checkNotNull(parent, "Parent directory was null."); String parentPath = parent.getCanonicalPath(); if (!torrent.isMultifile() && parent.isFile()) return new FileStorage(parent, torrent.getSize()); List<FileStorage> files = new LinkedList<FileStorage>(); long offset = 0L; for (Torrent.TorrentFile file : torrent.getFiles()) { // TODO: Files.simplifyPath() is a security check here to avoid jail-escape. // However, it uses "/" not File.separator internally. String path = Files.simplifyPath("/" + file.path); File actual = new File(parent, path); String actualPath = actual.getCanonicalPath(); if (!actualPath.startsWith(parentPath)) throw new SecurityException("Torrent file path attempted to break directory jail: " + actualPath + " is not within " + parentPath); FileUtils.forceMkdir(actual.getParentFile()); files.add(new FileStorage(actual, offset, file.size)); offset += file.size;// w w w.j ava2s.c om } return new FileCollectionStorage(files, torrent.getSize()); }