Showing posts with label Audit. Show all posts
Showing posts with label Audit. Show all posts

Monday, May 24, 2021

Achieve Old Audit Data

 Achieve Old Audit Data

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE Rule PUBLIC "sailpoint.dtd" "sailpoint.dtd">
<Rule language="beanshell"  name="VIS Archive AuditEvent Rule">
  <Source>

		import java.util.List;
		import java.util.ArrayList;
		import java.util.Iterator;
		import java.lang.Object;
		import java.lang.Thread;
		import java.util.Date;
		import java.io.File;
		import java.util.Calendar;
		import java.io.PrintWriter;
		import java.io.StringWriter;		
		import sailpoint.object.Identity;
		import sailpoint.api.Terminator;
		import sailpoint.tools.Util;
		import sailpoint.object.Application;
		import sailpoint.object.Attributes;
		import sailpoint.object.AuditEvent;
		import sailpoint.server.Auditor;
		import sailpoint.tools.GeneralException;
                import sailpoint.object.*;
		import sailpoint.tools.Message;
		import sailpoint.object.Link;
		import sailpoint.task.TaskMonitor;
		import sailpoint.task.TaskManager;  
		import sailpoint.object.MessageTemplate;
		import sailpoint.tools.Message.Type;		
                import org.apache.commons.logging.Log;
                import org.apache.commons.logging.LogFactory;
                import java.sql.Connection;
                import java.sql.PreparedStatement;
                import java.sql.Types;
                import java.sql.ResultSet;

		Log log = LogFactory.getLog("vis.rule.archiveAuditEvent");
		taskResult.setProgress("Starting Rule Archive Audit Event..."); 
		context.saveObject(taskResult); 
		context.commitTransaction();
	
		public static String StackTraceAsString(Exception exception) {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			exception.printStackTrace(pw);
			return "\n" + sw.toString(); // stack trace as a string
		}
		
		public static Date generateDate(int daysToSet) {
			Calendar cal = Calendar.getInstance();
			//if value is not 0 then we will leave the expiration date to the date this method is called.
			cal.setTime(new Date());

			if (daysToSet != 0) {
				cal.add(Calendar.DAY_OF_YEAR, daysToSet);
			}
			return (cal.getTime());
		}
    
  public static void doArchive(AuditEvent paramAuditEvent,Connection conn){
    
        String str = paramAuditEvent.toXml();
        PreparedStatement preparedStatement =null;
	  
    try{
        preparedStatement = conn.prepareStatement(INSERT_SQL);
        preparedStatement.setLong(1, Long.valueOf(new Date().getTime()));
        preparedStatement.setString(2, paramAuditEvent.getId());
	    preparedStatement.setLong(3, Long.valueOf(paramAuditEvent.getCreated().getTime()));     
	    if(  null != paramAuditEvent.getModified()){
	    preparedStatement.setLong(4,  Long.valueOf(paramAuditEvent.getModified().getTime()) );
        }else{
        preparedStatement.setNull(4,Types.NUMERIC);
        }   
	    if(null != paramAuditEvent.getOwner()){
        preparedStatement.setString(5, paramAuditEvent.getOwner().toString());
        }else{
        preparedStatement.setString(5, null);
        }     
	    if(null != paramAuditEvent.getAssignedScope()){
        preparedStatement.setString(6, paramAuditEvent.getAssignedScope().toString());
        }else{
        preparedStatement.setString(6, null);
        }	  
	    preparedStatement.setString(7, paramAuditEvent.getAssignedScopePath());
	    preparedStatement.setString(8, paramAuditEvent.getInterface());
	    preparedStatement.setString(9, paramAuditEvent.getSource());
	    preparedStatement.setString(10, paramAuditEvent.getAction());
	    preparedStatement.setString(11, paramAuditEvent.getTarget());
	    preparedStatement.setString(12, paramAuditEvent.getApplication());
	    preparedStatement.setString(13, paramAuditEvent.getAccountName());
	    preparedStatement.setString(14, paramAuditEvent.getInstance());
            preparedStatement.setString(15, paramAuditEvent.getAttributeName());
            preparedStatement.setString(16, paramAuditEvent.getAttributeValue());
	    preparedStatement.setString(17, paramAuditEvent.getTrackingId());
      if(null != paramAuditEvent.getAttributes()){
	    preparedStatement.setString(18,  paramAuditEvent.getAttributes().toString());
      }else{
            preparedStatement.setString(18, null);
      }
            preparedStatement.setString(19, paramAuditEvent.getString1());
	    preparedStatement.setString(20, paramAuditEvent.getString2());
	    preparedStatement.setString(21, paramAuditEvent.getString3());
	    preparedStatement.setString(22, paramAuditEvent.getString4());
	    preparedStatement.setString(23, str.substring(str.indexOf("AuditEvent")));
            preparedStatement.executeUpdate();
    }catch (Exception e){
       log.debug("Exception in doArchive method during audit event table archive"+e);
    }finally{
       if( null != preparedStatement){
           preparedStatement.close();
       }	    
    }	       
  }
  
  public static boolean isAuditArchived(String paramString,Connection conn){
   // log.debug("Enter into method isAuditArchived: Audit Event ObjectID: " + paramString);
    PreparedStatement localPreparedStatement =null;
    ResultSet localResultSet =null;
    boolean result = false;
    try{
     String str = "SELECT  * FROM idc_auditevent_archive where id = ?";
     localPreparedStatement= conn.prepareStatement(str);
     localPreparedStatement.setString(1, paramString);
     localResultSet = localPreparedStatement.executeQuery();
     while (localResultSet.next()) {
            result = true;
        }  
    }catch(Exception e){
      log.debug("Exception in isAuditArchived method "+e);
      result = true;
    }finally{
      if(null != localResultSet){
        localResultSet.close();
      }
      if(null != localPreparedStatement){
      localPreparedStatement.close();
      }
    }    
    return result;    
  }
 
	//Create custom table similar to SPT_AUDIT_EVENT
    public static String INSERT_SQL = "INSERT INTO sp_auditevent_archive (archived, id, created, modified, owner, assigned_scope, assigned_scope_path,interface, source,action,target,application,account_name,instance,attribute_name, attribute_value, tracking_id, attributes,string1,string2,string3,string4,rawdata) VALUES (?, ?,?, ?, ?,?, ?,?, ?, ?,?, ?,?, ?, ?,?, ?,?, ?, ?, ?, ?, ?)";	
	
	String summaryMessage = "";
	String status = "Completed";
        int completionCount = 0;
        String endDay=config.get("ENDDAY");
        String startDay=config.get("STARTDAY");
	log.debug("Fetching the parameters STARTDAY" + startDay );
        log.debug("Fetching the parameters ENDDAY" + endDay );
		QueryOptions qo = new QueryOptions();
	//	int endDaysInPast = (-128);
   //   int startDaysInPast=(-130);
   
    int endDaysInPast = Integer.parseInt(endDay);
    int startDaysInPast = Integer.parseInt(startDay);
    Connection conn=context.getConnection();
    List filters = new ArrayList();
    filters.add(Filter.ge("created", generateDate( startDaysInPast )));
    filters.add(Filter.le("created", generateDate( endDaysInPast )));
    Filter f=Filter.and(filters);
		qo.addFilter( f );
		qo.setDistinct(true);

	int count = context.countObjects(AuditEvent.class, qo);
	log.debug("Found: " + count + " audit events that match filter!");
		
	taskResult.setProgress("Found: " + count + " that match filter to archive!"); 
        context.saveObject(taskResult); 
        context.commitTransaction();
		
	String allowUpdateStr = Util.otos(config.get("AllowRemoval"));
	boolean allowUpdateB = false;

		if (null == allowUpdateStr) {
			taskResult.addMessage(sailpoint.tools.Message.error(("AllowRemoval variable is required. Please provide either true or false!"), null));
			taskResult.setCompletionStatus(TaskResult.CompletionStatus.Error);
			summaryMessage = "FAILED, AllowRemoval variable is required. Please provide either true or false!";
			status = "Error";
			
		} else {
			allowUpdateB = Util.otob(allowUpdateStr);
	
			try{
				Iterator iterator = context.search(AuditEvent.class, qo);
				taskResult.setProgress("Allowing removal: " + allowUpdateB); 
				context.saveObject(taskResult); 
				context.commitTransaction();
				StringBuilder sb = new StringBuilder();
				
				while( iterator.hasNext() ){
					AuditEvent auditEvent = (AuditEvent)iterator.next();
					String details = auditEvent.getId();				
					if(allowUpdateB &amp;&amp;!isAuditArchived(details,conn)){
                                        doArchive(auditEvent,conn);
						Terminator terminator = new Terminator(context);
						terminator.deleteObject(auditEvent);
                                                completionCount++;
                    }else{
                                        log.debug("Aleady archive Audit Event ID" + details );
                                        continue;
                    }									
					if( sb.length() > 0 ){
						sb.append(", ");
					}			
				}
				
				Util.flushIterator(iterator);
				
				taskResult.setCompletionStatus(TaskResult.CompletionStatus.Success);
				taskResult.setAttribute("_objectsUpdated", sb.toString() );				
				summaryMessage = "Successfully Deleted [ " + completionCount + " ] AuditEvents";
				status = "Success";
			
			} catch (Exception e){
				taskResult.setCompletionStatus(TaskResult.CompletionStatus.Error);
				taskResult.addMessage(sailpoint.tools.Message.error( ("Error Message: " + e.getMessage() + " stackTrace: " + StackTraceAsString(e)), null));
				summaryMessage = "Error Message: " + e.getMessage() + " stackTrace: " + StackTraceAsString(e);
				status = "Error";
                                log.debug("Exception in auditevent archive rule"+e);
        
            }finally{
                conn.close();
            }
		}
		taskResult.setAttribute("_totalObjectsUpdated",  Util.otos(completionCount));
		taskResult.setAttribute("_allowUpdate", Util.otos(allowUpdateB));
		taskResult.setAttribute("_summary",  summaryMessage);
		
		log.debug("Completed Deleting [ " + completionCount + " ] AuditEvents");		
		return(status);

  </Source>
</Rule>

Monday, November 18, 2019

Sailpoint IIQ Audit WorkFlow using OOTB Audit Method

If you want to add custom auditing to existing Audit method in a workflow or any where in the call etc., it's as easy as below, creating and call a audit method and setting the Action, Source, Target and values.

Here we need to make sure that we are adding proper action and source so that it's easily tracked.  

<Step action="call:audit" icon="Audit" name="Audit" posX="920" posY="91">
    <Arg name="string1" value="value1"/>
    <Arg name="string2" value="value2"/>
    <Arg name="string3" value="value3"/>
    <Arg name="string4" value="value4"/>
    <Arg name="action" value="Service Account Management"/>
    <Arg name="source" value="Service Account Management"/>
    <Arg name="target" value="spadmin"/>
    <Description>This step is use to Audit the Operation performed and the Values set during the operation.</Description>
    <Transition to="Stop"/>
  </Step>


Enable the Audit from the Audit Config Object from the Sailpoint IIQ Debug Page  








Use the Advance Analytics and Use Search Type as Audit to see the Entry


Thursday, September 12, 2019

Sailpoint IdentityIQ Custom Auditing Sample code


If you want add custom auditing to your beanshell in a rule, task or workflow or any where in the call etc, it's as easy as below , creating the new AuditEvent and setting the Action, Source, Target and values.

Here we need to make sure that we are adding proper action and source so that it's easily tracked . 


import sailpoint.api.SailPointContext;
import java.text.SimpleDateFormat;
import sailpoint.object.AuditEvent;
 
     public void customAudit(SailPointContext context) throws GeneralException{
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
  format.setTimeZone(TimeZone.getTimeZone("CST"));
  AuditEvent auditEvent = new AuditEvent();
  auditEvent.setAction("Custom Action");
  auditEvent.setSource("Custom Source");
  auditEvent.setTarget("vkejriwal");
  auditEvent.setString1("Timestamp: " + format.format(new Date()));
  auditEvent.setString2("User Name: " + "vkejriwal");
  auditEvent.setString3("IP: " + "127.0.0.1");
  context.saveObject(auditEvent);
  context.commitTransaction();
  
 }


Custom Audit which is added can be easily seen using the Advance Analytics .