List of usage examples for java.lang SecurityException SecurityException
public SecurityException(Throwable cause)
From source file:org.kawanfw.sql.servlet.sql.ServerCallableStatement.java
/** * Execute the passed SQL Statement and return: <br> * - The result set as a List of Maps for SELECT statements. <br> * - The return code for other statements * /*from w w w .ja v a 2 s. com*/ * @param sqlOrder * the qsql order * @param sqlParms * the sql parameters * @param out * the output stream where to write to result set output * * * @throws SQLException */ private void callStatement(OutputStream out) throws SQLException, IOException { String sqlOrder = callableStatementHolder.getSqlOrder(); debug("callableStatementHolder: " + callableStatementHolder.getSqlOrder()); debug("sqlOrder : " + sqlOrder); CallableStatement callableStatement = null; callableStatement = connection.prepareCall(sqlOrder); Map<Integer, Integer> parameterTypes = null; Map<Integer, String> parameterStringValues = null; // Class to set all the statement parameters ServerCallableStatementParameters serverCallableStatementParameters = null; try { ServerSqlUtilCallable.setCallableStatementProperties(callableStatement, callableStatementHolder); parameterTypes = callableStatementHolder.getParameterTypes(); parameterStringValues = callableStatementHolder.getParameterStringValues(); debug("before serverCallableStatementParameters"); serverCallableStatementParameters = new ServerCallableStatementParameters(username, fileConfigurator, callableStatement, callableStatementHolder); serverCallableStatementParameters.setParameters(); // Throws a SQL exception if the order is not authorized: debug("before new SqlSecurityChecker()"); boolean isAllowedAfterAnalysis = true; /* * boolean isAllowedAfterAnalysis = sqlConfigurator * .allowStatementAfterAnalysis(username, connection, sqlOrder, * serverPreparedStatementParameters .getParameterValues()); */ if (!isAllowedAfterAnalysis) { String ipAddress = request.getRemoteAddr(); SqlConfiguratorCall.runIfStatementRefused(sqlConfigurator, username, connection, ipAddress, sqlOrder, serverCallableStatementParameters.getParameterValues()); String message = Tag.PRODUCT_SECURITY + " [" + "{Callable Statement not authorized}" + "{sql order : " + sqlOrder + "}" + "{sql parms : " + parameterTypes + "}" + "{sql values: " + parameterStringValues + "}]"; throw new SecurityException(message); } isAllowedAfterAnalysis = SqlConfiguratorCall.allowResultSetGetMetaData(sqlConfigurator, username, connection); debug("before callableStatement.executeQuery() / execute"); ServerSqlUtil.setMaxRowsToReturn(callableStatement, sqlConfigurator); ResultSet rs = null; boolean hasResultSet = false; if (isExecuteRaw) { hasResultSet = callableStatement.execute(); if (hasResultSet) { rs = callableStatement.getResultSet(); } } else { rs = callableStatement.executeQuery(); } // 1) Update and send back the CallableStatementHolder: updateCallableStatementHolderValues(callableStatement); //out.write(TransferStatus.SEND_OK + CR_LF); ServerSqlManager.writeLine(out, TransferStatus.SEND_OK); String jsonString = CallableStatementHolderTransportJson.toJson(callableStatementHolder); boolean doEncryptCallableStatement = SqlConfiguratorCall.encryptResultSet(sqlConfigurator); if (doEncryptCallableStatement) { jsonString = JsonLineEncrypter.encrypt(jsonString, commonsConfigurator); } //out.write(jsonString + CR_LF); ServerSqlManager.writeLine(out, jsonString); // 2) Send back the result set: if (hasResultSet || !isExecuteRaw) { try { // Horrible hack because ResultSetWriter is in common CE/EE // code and // we can't modify it now (to be clean in next CE version): StatementHolder statementHolder = new StatementHolder(); statementHolder.setHtmlEncodingOn(callableStatementHolder.isHtmlEncodingOn()); ResultSetWriter resultSetWriter = new ResultSetWriter(request, out, commonsConfigurator, fileConfigurator, sqlConfigurator, username, sqlOrder, statementHolder); resultSetWriter.write(rs); } finally { if (rs != null) { rs.close(); } } } else { // Write a line saying there is no Result Set! //out.write(CallableParms.NO_RESULT_SET + CR_LF); ServerSqlManager.writeLine(out, CallableParms.NO_RESULT_SET); } } catch (SQLException e) { ServerLogger.getLogger().log(Level.WARNING, Tag.PRODUCT_EXCEPTION_RAISED + CR_LF + "CallableStatement statement: " + sqlOrder + CR_LF + "- sql order : " + sqlOrder + CR_LF + "- sql parms : " + parameterTypes + CR_LF + "- sql values: " + parameterStringValues + CR_LF + "- exception : " + e.toString()); throw e; } finally { // Close the ServerPreparedStatementParameters if (serverCallableStatementParameters != null) { serverCallableStatementParameters.close(); } if (callableStatement != null) { callableStatement.close(); } // Clean all parameterTypes = null; parameterStringValues = null; serverCallableStatementParameters = null; } }
From source file:cn.newgxu.lab.info.controller.AuthController.java
/** ?? */ private AuthorizedUser checkAdmin(HttpSession session) { AuthorizedUser user = this.checkLogin(session); if (!user.getType().equals(AccountType.ADMIN)) { throw new SecurityException("?????"); }/*from w ww. jav a 2s . c o m*/ return user; }
From source file:org.openanzo.activemq.internal.SecurityBroker.java
@Override public void addConnection(ConnectionContext connectionContext, ConnectionInfo info) throws Exception { if (connectionContext.getSecurityContext() == null) { IOperationContext context = null; try {//w w w . j av a 2 s . c o m context = new BaseOperationContext(ADD_CONNECTION, info.getConnectionId().toString(), principal); context.setMDC(); AnzoPrincipal principal = authenticationService.authenticateUser(context, info.getUserName(), info.getPassword()); if (principal != null) { idToUser.put(info.getUserName(), principal.getUserURI()); ServerSecurityContext securityContext = userSecurityContextMap.get(principal.getName()); if (securityContext == null) { securityContext = new ServerSecurityContext(principal); userSecurityContextMap.put(principal.getName(), securityContext); securityContexts.add(securityContext); } connectionContext.setSecurityContext(securityContext); Set<ConnectionContext> conns = userConnection.get(info.getUserName()); if (conns == null) { conns = new CopyOnWriteArraySet<ConnectionContext>(); userConnection.put(info.getUserName(), conns); } conns.add(connectionContext); connectionContext.setProducerFlowControl(false); } else { MDC.put(LogUtils.REMOTE_ADDRESS, connectionContext.getConnection().getRemoteAddress()); MDC.put(LogUtils.USER, info.getUserName()); String errorMsg = Messages.getString(ExceptionConstants.COMBUS.ERROR_LOGGING_IN); log.error(LogUtils.SECURITY_MARKER, errorMsg); MDC.clear(); throw new SecurityException(errorMsg); } } finally { if (context != null) { context.clearMDC(); } } } connections.add(info.getConnectionId().getValue()); super.addConnection(connectionContext, info); }
From source file:org.kawanfw.sql.servlet.sql.ServerStatementRawExecute.java
/** * Execute the passed SQL PreparedStatement as execute() sand return: <br> * - The result set as a List of Maps for SELECT statements. <br> * - The return code for other statements * /*from w w w. ja v a 2 s. c om*/ * @param sqlOrder * the qsql order * @param sqlParms * the sql parameters * @param out * the output stream where to write to result set output * * * @throws SQLException */ private void executePrepStatement(OutputStream out) throws SQLException, IOException { String sqlOrder = statementHolder.getSqlOrder(); PreparedStatement preparedStatement = null; boolean usesAutoGeneratedKeys = false; if (statementHolder.getAutoGeneratedKeys() != -1) { preparedStatement = connection.prepareStatement(sqlOrder, statementHolder.getAutoGeneratedKeys()); usesAutoGeneratedKeys = true; } else if (statementHolder.getColumnIndexesAutogenerateKeys().length != 0) { preparedStatement = connection.prepareStatement(sqlOrder, statementHolder.getColumnIndexesAutogenerateKeys()); usesAutoGeneratedKeys = true; } else if (statementHolder.getColumnNamesAutogenerateKeys().length != 0) { preparedStatement = connection.prepareStatement(sqlOrder, statementHolder.getColumnNamesAutogenerateKeys()); usesAutoGeneratedKeys = true; } else { preparedStatement = connection.prepareStatement(sqlOrder); } Map<Integer, Integer> parameterTypes = null; Map<Integer, String> parameterStringValues = null; // Class to set all the statement parameters ServerPreparedStatementParameters serverPreparedStatementParameters = null; try { ServerSqlUtil.setStatementProperties(preparedStatement, statementHolder); parameterTypes = statementHolder.getParameterTypes(); parameterStringValues = statementHolder.getParameterStringValues(); if (!SqlConfiguratorCall.allowExecute(sqlConfigurator, username, connection)) { String ipAddress = request.getRemoteAddr(); SqlConfiguratorCall.runIfStatementRefused(sqlConfigurator, username, connection, ipAddress, sqlOrder, new Vector<Object>()); String message = Tag.PRODUCT_SECURITY + " [" + "{Prepared Statement not authorized for execute}" + "{sql order : " + sqlOrder + "}" + "{sql parms : " + parameterTypes + "}" + "{sql values: " + parameterStringValues + "}]"; throw new SecurityException(message); } debug("before ServerPreparedStatementParameters"); serverPreparedStatementParameters = new ServerPreparedStatementParameters(request, username, fileConfigurator, preparedStatement, statementHolder); serverPreparedStatementParameters.setParameters(); // Throws a SQL exception if the order is not authorized: debug("before new SqlSecurityChecker()"); boolean isAllowed = sqlConfigurator.allowStatementAfterAnalysis(username, connection, sqlOrder, serverPreparedStatementParameters.getParameterValues()); if (!isAllowed) { String ipAddress = request.getRemoteAddr(); SqlConfiguratorCall.runIfStatementRefused(sqlConfigurator, username, connection, ipAddress, sqlOrder, serverPreparedStatementParameters.getParameterValues()); String message = Tag.PRODUCT_SECURITY + " [" + "{Prepared Statement not authorized}" + "{sql order : " + sqlOrder + "}" + "{sql parms : " + parameterTypes + "}" + "{sql values: " + parameterStringValues + "}]"; throw new SecurityException(message); } debug("before preparedStatement.execute()"); ServerSqlUtil.setMaxRowsToReturn(preparedStatement, sqlConfigurator); boolean isResultSet = preparedStatement.execute(); if (isResultSet) { ResultSet rs = preparedStatement.getResultSet(); try { //out.write(TransferStatus.SEND_OK + CR_LF); ServerSqlManager.writeLine(out, TransferStatus.SEND_OK); ResultSetWriter resultSetWriter = new ResultSetWriter(request, out, commonsConfigurator, fileConfigurator, sqlConfigurator, username, sqlOrder, statementHolder); resultSetWriter.write(rs); } finally { if (rs != null) rs.close(); } } else { int rc = preparedStatement.getUpdateCount(); //out.write(TransferStatus.SEND_OK + CR_LF); //out.write("getUpdateCount=" + rc + CR_LF); ServerSqlManager.writeLine(out, TransferStatus.SEND_OK); ServerSqlManager.writeLine(out, "getUpdateCount=" + rc); // Write the preparedStatement.getGeneratedKeys() on the stream // if necessary if (usesAutoGeneratedKeys) { ResultSet rs = preparedStatement.getGeneratedKeys(); try { ResultSetWriter resultSetWriter = new ResultSetWriter(request, out, commonsConfigurator, fileConfigurator, sqlConfigurator, username, sqlOrder, statementHolder); resultSetWriter.write(rs); } finally { if (rs != null) rs.close(); } } } } catch (SQLException e) { ServerLogger.getLogger().log(Level.WARNING, Tag.PRODUCT_PRODUCT_FAIL + CR_LF + "Prepared statement: " + sqlOrder + CR_LF + "- sql order : " + sqlOrder + CR_LF + "- sql parms : " + parameterTypes + CR_LF + "- sql values: " + parameterStringValues + CR_LF + "- exception : " + e.toString()); throw e; } finally { // Close the ServerPreparedStatementParameters if (serverPreparedStatementParameters != null) { serverPreparedStatementParameters.close(); } if (preparedStatement != null) { preparedStatement.close(); } } }
From source file:com.turn.ttorrent.client.SharedTorrent.java
/** * Create a new shared torrent from meta-info binary data. * * @param torrent The meta-info byte data. * @param parent The parent directory or location the torrent files. * @param seeder Whether we're a seeder for this torrent or not (disables * validation).//w w w.j av a 2s. c om * @param requestStrategy The request strategy implementation. * @throws FileNotFoundException If the torrent file location or * destination directory does not exist and can't be created. * @throws IOException If the torrent file cannot be read or decoded. */ public SharedTorrent(byte[] torrent, File parent, boolean seeder, RequestStrategy requestStrategy) throws FileNotFoundException, IOException, NoSuchAlgorithmException { super(torrent, seeder); if (parent == null || !parent.isDirectory()) { throw new IllegalArgumentException("Invalid parent directory!"); } String parentPath = parent.getCanonicalPath(); try { this.pieceLength = this.decoded_info.get("piece length").getInt(); this.piecesHashes = ByteBuffer.wrap(this.decoded_info.get("pieces").getBytes()); if (this.piecesHashes.capacity() / Torrent.PIECE_HASH_SIZE * (long) this.pieceLength < this.getSize()) { throw new IllegalArgumentException( "Torrent size does not " + "match the number of pieces and the piece size!"); } } catch (InvalidBEncodingException ibee) { throw new IllegalArgumentException("Error reading torrent meta-info fields!"); } List<FileStorage> files = new LinkedList<FileStorage>(); long offset = 0L; for (Torrent.TorrentFile file : this.files) { File actual = new File(parent, file.file.getPath()); if (!actual.getCanonicalPath().startsWith(parentPath)) { throw new SecurityException("Torrent file path attempted " + "to break directory jail!"); } actual.getParentFile().mkdirs(); files.add(new FileStorage(actual, offset, file.size)); offset += file.size; } this.bucket = new FileCollectionStorage(files, this.getSize()); this.stop = false; this.uploaded = 0; this.downloaded = 0; this.left = this.getSize(); this.initialized = false; this.pieces = new Piece[0]; this.rarest = Collections.synchronizedSortedSet(new TreeSet<Piece>()); this.completedPieces = new BitSet(); this.requestedPieces = new BitSet(); //TODO: should switch to guice this.requestStrategy = requestStrategy; }
From source file:net.es.netshell.kernel.users.Users.java
public CommandResponse createUser(UserProfile newUser) { if (BootStrap.getBootStrap().isStandAlone()) { throw new SecurityException("not allowed"); }/* w w w.j a v a 2 s .co m*/ Method method = null; CommandResponse commandResponse; String resMessage = null; boolean resCode = false; try { method = KernelThread.getSysCallMethod(this.getClass(), "do_createUser"); // Access per Application UserAccess currentUserAccess = UserAccess.getUsers(); KernelThread kt = KernelThread.currentKernelThread(); String currentUserName = kt.getUser().getName(); // Check if user is authorized to create users if (KernelThread.currentKernelThread().isPrivileged() || currentUserAccess.isAccessPrivileged(currentUserName, "user:create")) { KernelThread.doSysCall(this, method, newUser, true); resCode = true; resMessage = "User added"; } else { resCode = false; resMessage = "Operation Not Permitted"; } } catch (UserAlreadyExistException e) { e.printStackTrace(); resCode = false; resMessage = "User already exists"; } catch (NoSuchMethodException e) { e.printStackTrace(); resCode = false; resMessage = "Method not implemented"; } catch (UserClassException e) { e.printStackTrace(); resCode = false; resMessage = "User class must be root or user"; } catch (Exception e) { e.printStackTrace(); resCode = false; resMessage = "Error in operation"; } commandResponse = new CommandResponse(resMessage, resCode); return commandResponse; }
From source file:edu.ku.brc.af.auth.specify.SpecifySecurityMgr.java
/** * Checks whether current user has the permission defined by the permission class, * the name and actions provided. This method is protected because there is only * one class of permissions being used so far: BasicSpPermission. When new permissions * classes are created, this method can be made public * /*from www . j ava2 s .co m*/ * @param permissionClass Class of the permission being tested * @param name Type and target of permission * @param actions Actions (any combination of view, add, modify, delete actions) * @return Whether the user has the permission or not */ protected boolean checkPermission(final Class<?> permissionClass, final String name, final String actions) { if (!(BasicSpPermission.class.isAssignableFrom(permissionClass))) { throw new SecurityException( permissionClass.getName() + " class is not part of Specify permission hierarchy."); //$NON-NLS-1$ } Constructor<?> constructor = null; BasicSpPermission perm = null; try { constructor = permissionClass.getConstructor(String.class, String.class); perm = (BasicSpPermission) constructor.newInstance(name, actions); } catch (Exception e) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifySecurityMgr.class, e); throw new RuntimeException(e); } return checkPermission(perm); }
From source file:org.sakaiproject.iclicker.tool.ToolController.java
public void processInstructor(PageContext pageContext, HttpServletRequest request) { // admin/instructor check if (!this.isAdmin() && !this.isInstructor()) { throw new SecurityException("Current user is not an instructor and cannot access the instructor view"); }/*from w w w.ja v a 2 s. c o m*/ String courseId = request.getParameter("courseId"); pageContext.setAttribute("courseId", courseId); if (courseId != null) { pageContext.setAttribute("courseTitle", this.getLogic().getCourseTitle(courseId)); } List<Course> courses = logic.getCoursesForInstructorWithStudents(courseId); pageContext.setAttribute("courses", courses); pageContext.setAttribute("coursesCount", courses.size()); pageContext.setAttribute("showStudents", false); if (courseId != null && courses.size() == 1) { Course course = courses.get(0); pageContext.setAttribute("showStudents", true); pageContext.setAttribute("course", course); pageContext.setAttribute("students", course.students); pageContext.setAttribute("studentsCount", course.students.size()); } // SSO handling pageContext.setAttribute("ssoEnabled", logic.isSingleSignOnEnabled()); }
From source file:org.gwtwidgets.server.spring.GWTRPCServiceExporter.java
/** * Handles an exception which is raised when a method invocation with bad * arguments is attempted. This implementation throws a * {@link SecurityException}. For details on arguments please consult * {@link #invokeMethodOnService(Object, Method, Object[], RPCRequest)}. * /*w w w . j a v a 2s . c o m*/ * @param e * Exception thrown * @param service * @param targetMethod * @return RPC encoded response (such as an RPC client exception) */ protected String handleIllegalArgumentException(IllegalArgumentException e, Object service, Method targetMethod, RPCRequest rpcRequest) { SecurityException securityException = new SecurityException( "Blocked attempt to invoke method " + targetMethod); securityException.initCause(e); throw securityException; }
From source file:com.github.michalbednarski.intentslab.Utils.java
@TargetApi(13) // Function handles all supported api levels public static InputStream dumpSystemService(Context context, String serviceName, final String[] arguments) throws Exception { // Check if we have permission to invoke dump from our process final boolean canDumpLocally = context.getPackageManager().checkPermission(android.Manifest.permission.DUMP, context.getPackageName()) == PackageManager.PERMISSION_GRANTED; // On versions without createPipe() just execute dumpsys if (android.os.Build.VERSION.SDK_INT < 9) { if (!canDumpLocally) { throw new Exception("Dumping is not supported on this system version"); }// ww w.j av a 2 s. c o m String[] progArray = new String[arguments != null ? 2 + arguments.length : 2]; progArray[0] = "dumpsys"; progArray[1] = serviceName; if (arguments != null) { System.arraycopy(arguments, 0, progArray, 2, arguments.length); } return Runtime.getRuntime().exec(progArray).getInputStream(); } // Get service final Class<?> serviceManager = Class.forName("android.os.ServiceManager"); final IBinder service = (IBinder) serviceManager.getMethod("getService", String.class).invoke(null, serviceName); // Check permissions and get remote interface if needed IRemoteInterface remoteInterface = null; if (!canDumpLocally) { remoteInterface = RunAsManager.getRemoteInterfaceForSystemDebuggingCommands(); if (remoteInterface == null) { throw new SecurityException("Process has no permission to dump services"); } } // Create pipe, write(pipe[0]) -> read(pipe[1]) final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe(); final ParcelFileDescriptor readablePipe = pipe[0]; final ParcelFileDescriptor writablePipe = pipe[1]; try { // Execute dump if (canDumpLocally) { if (android.os.Build.VERSION.SDK_INT >= 13) { service.dumpAsync(writablePipe.getFileDescriptor(), arguments); writablePipe.close(); } else { (new Thread() { @Override public void run() { try { service.dump(writablePipe.getFileDescriptor(), arguments); writablePipe.close(); } catch (Exception e) { // TODO: can we handle this? e.printStackTrace(); } } }).start(); } } else { remoteInterface.dumpServiceAsync(service, writablePipe, arguments); writablePipe.close(); } // If anything went wrong, close pipe and rethrow } catch (Throwable e) { readablePipe.close(); writablePipe.close(); throwUnchecked(e); throw new Error(); // Unreachable } // Return stream that will ensure closing fd return new FileInputStream(readablePipe.getFileDescriptor()) { @Override public void close() throws IOException { super.close(); readablePipe.close(); } }; }